how to do list comprehension with if?
List comprehension with an if
condition in Python allows you to create a new list by iterating over an existing iterable and including only the elements that satisfy a specific condition.
Example 1: Simple List Comprehension with if
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# List comprehension with if condition to select even numbers
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) # Output: [2, 4, 6, 8, 10]
Example 2: List Comprehension with if
and else
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# List comprehension with if-else to classify numbers as 'Even' or 'Odd'
classified_numbers = ['Even' if num % 2 == 0 else 'Odd' for num in numbers]
print(classified_numbers) # Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']
Example 3: Nested List Comprehension with if
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Flatten the matrix and select only the elements greater than 4
flattened_and_filtered = [num for row in matrix for num in row if num > 4]
print(flattened_and_filtered) # Output: [5, 6, 7, 8, 9]
Summary:
- With
if
only:[expression for item in iterable if condition]
- With
if
andelse
:[expression_if_true if condition else expression_if_false for item in iterable]
- Nested with
if
:[expression for sublist in outer_list for item in sublist if condition]
This concise and readable syntax is a powerful feature in Python for transforming and filtering lists in a single line.
"Answer Generated by OpenAI's ChatGPT"