List Comprehension III - If Else If

Using if-else Statements in Python List Comprehensions

Using if-else Statements in Python List Comprehensions


If-else statements are a fundamental control structure in Python, allowing the code to execute different actions based on whether a certain condition is met. Combining this feature with list comprehensions can create highly dynamic and efficient code. In this blog post, we'll explore some complex examples of using if-else statements within list comprehensions.

Assigning Values Based on a Condition

One common use case is assigning different values based on a condition. Let's create a new list where each element is determined by the parity of the corresponding element in the original list:


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

In this example, we assign 'Even' if the number is even, and 'Odd' if the number is odd.

Performing Different Operations Based on a Condition

Another use case is to perform different operations on the list elements based on a condition. For example, let's square the number if it's odd, and halve it if it's even:


old_list = [1, 2, 3, 4, 5]
new_list = [i**2 if i % 2 != 0 else i / 2 for i in old_list]
print(new_list)  # Outputs: [1, 1.0, 9, 2.0, 25]

Multiple Conditions

If-else statements within list comprehensions can handle multiple conditions as well. Let's assign 'Positive', 'Negative', or 'Zero' to a new list based on the values of the old list:


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']

In this example, we use a nested if-else statement to handle the three possible cases.

If-else statements can undoubtedly add significant flexibility to your list comprehensions. But remember, while they make your code more powerful, they can also make it more complex and harder to read if overused. Always balance between power and readability when writing code.

Comments

Popular posts from this blog

Drawing Tables with ReportLab: A Comprehensive Example

Blog Topics

DataFrame groupby agg style bar