List comprehensions provide a concise way to create lists in Python. They are commonly used to transform or filter items from an existing iterable (like a list, string, or range) into a new list.
if condition.if...else expressions for conditional values.The general syntax of a list comprehension is:
new_list = [expression for item in iterable if condition]
item * 2).list, range, string, etc.Create a new list by applying an expression to each item of an existing list.
fruits = ["apple", "banana", "cherry"]
new_list = [fruit.upper() for fruit in fruits]
print(new_list)
Add an if condition to filter the results.
numbers = [10, 15, 20, 25, 30]
even_numbers = [n for n in numbers if n % 2 == 0]
print(even_numbers)
Include an inline if...else expression to decide what value goes into the list.
numbers = [1, 2, 3, 4, 5]
result = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(result)
Use nested list comprehensions for working with multiple lists or 2D data.
matrix = [[1, 2], [3, 4], [5, 6]]
flattened = [num for row in matrix for num in row]
print(flattened)
Basic Transformation:
['APPLE', 'BANANA', 'CHERRY']
Filtering with Condition:
[10, 20, 30]
Using if...else:
['odd', 'even', 'odd', 'even', 'odd']
Nested / Flattening:
[1, 2, 3, 4, 5, 6]
In each case, the list comprehension loops over an existing iterable and builds a new list. Conditions (if) decide which elements are included, while inline if...else chooses which value to store for each element.
for loops.