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

Your email address will not be published. Required fields are marked *