List Comprehension in Python ๐
๐น What is List Comprehension?
List comprehension is a concise way to create lists in Python. Instead of using a loop to generate a list, you can use a single-line expression that makes the code more readable and efficient.
๐ก Basic Syntax:
new_list = [expression for item in iterable if condition]
- expression โ The operation to perform on each item.
- item โ The variable representing each element in the iterable.
- iterable โ The source (list, tuple, range, etc.).
- condition (optional) โ A filter that selects specific items.
๐น Example 1: Creating a List
๐ก Without List Comprehension
squares = []
for x in range(5):
squares.append(x**2)
print(squares) # Output: [0, 1, 4, 9, 16]
โ With List Comprehension
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
๐ฏ Much shorter and cleaner!
๐น Example 2: Filtering with a Condition
๐ก Without List Comprehension
even_numbers = []
for x in range(10):
if x % 2 == 0:
even_numbers.append(x)
print(even_numbers) # Output: [0, 2, 4, 6, 8]
โ With List Comprehension
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers) # Output: [0, 2, 4, 6, 8]
๐น Example 3: Applying Functions in List Comprehension
words = ["hello", "world", "python"]
uppercase_words = [word.upper() for word in words]
print(uppercase_words) # Output: ['HELLO', 'WORLD', 'PYTHON']
๐น Example 4: Nested List Comprehension
๐ก Creating a 2D matrix (3×3)
matrix = [[x for x in range(3)] for y in range(3)]
print(matrix)
# Output: [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
๐น Example 5: Using if-else
in List Comprehension
numbers = [1, 2, 3, 4, 5]
result = ["Even" if x % 2 == 0 else "Odd" for x in numbers]
print(result) # Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd']
๐น Example 6: Flattening a Nested List
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flattened = [num for sublist in nested_list for num in sublist]
print(flattened) # Output: [1, 2, 3, 4, 5, 6, 7, 8]
๐น Dictionary & Set Comprehensions (Bonus)
1๏ธโฃ Dictionary Comprehension
squares = {x: x**2 for x in range(5)}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
2๏ธโฃ Set Comprehension
unique_numbers = {x % 3 for x in range(10)}
print(unique_numbers) # Output: {0, 1, 2}
๐น Summary Table
Use Case | List Comprehension |
---|---|
Create a list | [x for x in iterable] |
Filter elements | [x for x in iterable if condition] |
Apply function | [func(x) for x in iterable] |
If-else condition | [x if condition else y for x in iterable] |
Nested lists | [[x for x in range(3)] for y in range(3)] |
๐ฏ Advantages of List Comprehension
โ
Faster Execution โ More efficient than loops.
โ
Concise & Readable โ Reduces lines of code.
โ
Memory Efficient โ Can use generators to reduce memory usage.
Would you like more real-world examples? ๐
Leave a Reply