List Comprehension - If Else if, Multiple Conditions

Multiple Conditions in Python List Comprehensions

Multiple Conditions in Python List Comprehensions


List comprehensions combined with if-else statements are a powerful tool in Python. When working with multiple conditions, they can significantly increase the flexibility of your code. Let's dive into four complex examples of list comprehensions with multiple conditions.

1. Categorizing Numbers into Even, Odd, and Zero

In this example, we create a new list where each element is 'Even', 'Odd', or 'Zero', based on the corresponding element in the original list:


old_list = [-2, -1, 0, 1, 2]
new_list = ['Even' if i % 2 == 0 else 'Odd' if i != 0 else 'Zero' for i in old_list]
print(new_list)  # Outputs: ['Even', 'Odd', 'Zero', 'Odd', 'Even']

2. Checking if Numbers Are Positive, Negative, or Zero

This time, we check if the numbers in our original list are positive, negative, or zero:


old_list = [-2, -1, 0, 1, 2]
new_list = ['Positive' if i > 0 else 'Negative' if i < 0 else 'Zero' for i in old_list]
print(new_list)  # Outputs: ['Negative', 'Negative', 'Zero', 'Positive', 'Positive']

3. Classifying Numbers by Size and Parity

In this example, we classify the numbers from our original list based on whether they're small (less than 10), large (greater than or equal to 10), even, or odd:


old_list = [2, 9, 10, 15]
new_list = ['Small & Even' if i < 10 and i % 2 == 0 else 'Small & Odd' if i < 10 else 'Large & Even' if i % 2 == 0 else 'Large & Odd' for i in old_list]
print(new_list)  # Outputs: ['Small & Even', 'Small & Odd', 'Large & Even', 'Large & Odd']

4. Transforming and Categorizing Strings

Finally, we transform the strings from our original list based on their length and whether they start with an 'a':


old_list = ['apple', 'banana', 'cherry', 'avocado', 'grape']
new_list = [word.upper() if len(word) > 5 and word[0] == 'a' else word for word in old_list]
print(new_list)  # Outputs: ['APPLE', 'banana', 'cherry', 'AVOCADO', 'grape']

As you can see, using multiple conditions within list comprehensions can make your code more flexible and dynamic. However, it can also make your code more complex. Always consider readability and code complexity when deciding how to structure your code.

Comments

Popular posts from this blog

Drawing Tables with ReportLab: A Comprehensive Example

Blog Topics

fillna