List Comprehension

Loading

List comprehension is a concise way to create lists in Python. It replaces traditional for loops with a shorter, more readable syntax.

Why Use List Comprehension?

More readable and concise than loops
Faster execution compared to traditional loops
Reduces the need for extra lines of code


1. Basic Syntax of List Comprehension

new_list = [expression for item in iterable if condition]
  • expression → Value to be added to the new list
  • item → Each element in the iterable
  • iterable → Source (e.g., list, range, string)
  • condition (optional) → Filters elements

2. Creating Lists Using List Comprehension

Example 1: Creating a List of Squares

squares = [x**2 for x in range(1, 6)]
print(squares)

Output:

[1, 4, 9, 16, 25]

Example 2: Filtering Even Numbers

evens = [x for x in range(10) if x % 2 == 0]
print(evens)

Output:

[0, 2, 4, 6, 8]

3. Using if-else in List Comprehension

If you need an if-else condition, it must be inside the expression.

Example: Labeling Even and Odd Numbers

labels = ["Even" if x % 2 == 0 else "Odd" for x in range(5)]
print(labels)

Output:

['Even', 'Odd', 'Even', 'Odd', 'Even']

4. Nested Loops in List Comprehension

Example: Cartesian Product (Pairs of Elements)

pairs = [(x, y) for x in range(3) for y in range(3)]
print(pairs)

Output:

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

5. List Comprehension with Strings

Example: Extracting Vowels from a String

text = "Hello World"
vowels = [char for char in text if char.lower() in "aeiou"]
print(vowels)

Output:

['e', 'o', 'o']

Example: Converting Strings to Uppercase

words = ["hello", "world"]
uppercase_words = [word.upper() for word in words]
print(uppercase_words)

Output:

['HELLO', 'WORLD']

6. List Comprehension with zip()

Example: Adding Corresponding Elements of Two Lists

list1 = [1, 2, 3]
list2 = [4, 5, 6]

sum_list = [x + y for x, y in zip(list1, list2)]
print(sum_list)

Output:

[5, 7, 9]

7. Flattening a Nested List Using List Comprehension

Example: Converting a 2D List into a 1D List

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = [num for row in matrix for num in row]
print(flat_list)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

8. Dictionary and Set Comprehension

Example: Dictionary Comprehension

squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict)

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Example: Set Comprehension

unique_chars = {char for char in "hello"}
print(unique_chars)

Output:

{'h', 'e', 'o', 'l'}

9. Performance Comparison: List Comprehension vs. Loops

Example: Squaring Numbers Using a Loop

numbers = []
for x in range(1, 1000000):
numbers.append(x**2)

Example: Squaring Numbers Using List Comprehension

numbers = [x**2 for x in range(1, 1000000)]

List Comprehension is Faster because it is optimized internally in Python.


10. When to Use List Comprehension?

Use list comprehension when:

  • You want a more compact and readable way to create lists.
  • Performance is important, as it is faster than loops.
  • You need filtering and transformations in a single line.

Avoid list comprehension when:

  • The logic is too complex (use loops for clarity).
  • Nested comprehensions make code hard to read.

Leave a Reply

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