List Comprehension in python
List comprehension is a concise and powerful way to create lists in Python. It allows you to generate, transform, and filter list items using a single line of code.
Compared to traditional for loops, list comprehensions are often shorter, more readable, and easier to write.
What is List Comprehension?
List comprehension creates a new list by applying an expression to each item in an iterable.
Syntax
[expression for item in iterable]
Example
numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
print(squares)
Output:
[1, 4, 9, 16, 25]
Creating a List Using a Loop
Without list comprehension:
numbers = [1, 2, 3, 4, 5]
squares = []
for num in numbers:
squares.append(num ** 2)
print(squares)
Output:
[1, 4, 9, 16, 25]
Using list comprehension produces the same result with less code.
List Comprehension with Conditions
You can add an condition to include only specific items.
if
Syntax
[expression for item in iterable if condition]
Example
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0] print(even_numbers)
Output:
[2, 4, 6]
Only even numbers are included in the new list.
Creating a List of Strings
Example
fruits = ["apple", "banana", "mango"]
uppercase_fruits = [fruit.upper() for fruit in fruits] print(uppercase_fruits)
Output:
['APPLE', 'BANANA', 'MANGO']
Using range() with List Comprehension
range()Example
numbers = [x for x in range(1, 6)] print(numbers)
Output:
[1, 2, 3, 4, 5]
Using an if-else Condition
if-elseYou can use conditional expressions inside list comprehensions.
Syntax
[expression_if_true if condition else expression_if_false for item in iterable]
Example
numbers = [1, 2, 3, 4, 5]
result = ["Even" if num % 2 == 0 else "Odd" for num in numbers] print(result)
Output:
['Odd', 'Even', 'Odd', 'Even', 'Odd']
List Comprehension with Strings
Example
word = "Python" letters = [letter for letter in word] print(letters)
Output:
['P', 'y', 't', 'h', 'o', 'n']
Nested List Comprehension
List comprehensions can also be nested.
Example
matrix = [[1, 2], [3, 4], [5, 6]]
flattened = [item for row in matrix for item in row]
print(flattened)
Output:
[1, 2, 3, 4, 5, 6]
Benefits of List Comprehension
- Reduces the amount of code.
- Improves readability for simple operations.
-
Often performs faster than equivalent
forloops. - Makes data transformation easier.
| Feature | Example |
|---|---|
| Basic list comprehension |
[x for x in numbers]
|
| With condition |
[x for x in numbers if x > 5]
|
With if-else
|
["Even" if x % 2 == 0 else "Odd" for x in numbers]
|
| Using strings |
[char for char in word]
|
Using range()
|
[x for x in range(5)]
|