List Comprehensions and Generators

1. Introduction

Python provides efficient ways to handle collections of data using list comprehensions and generators.

  • List comprehensions offer a concise way to create lists.
  • Generators help in memory-efficient iteration by generating values on the fly.

Let's explore both in detail! 


2. List Comprehensions

List comprehension provides a compact way to generate a new list from an existing sequence.

Syntax:

new_list = [expression for item in iterable if condition]

Example 1: Creating a List Using a Loop

Without list comprehension:

numbers = [1, 2, 3, 4, 5]
squared = []
for num in numbers:
    squared.append(num ** 2)
print(squared)  # Output: [1, 4, 9, 16, 25]

With list comprehension:

squared = [num ** 2 for num in numbers]
print(squared)  # Output: [1, 4, 9, 16, 25]

More concise and readable!


Example 2: List Comprehension with Condition

even_numbers = [num for num in range(10) if num % 2 == 0]
print(even_numbers)  # Output: [0, 2, 4, 6, 8]

Filters only even numbers


Example 3: Nested List Comprehensions

matrix = [[j for j in range(3)] for i in range(3)]
print(matrix)  
# Output: [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

Creates a 3×3 matrix using nested list comprehension


3. Generators in Python

A generator is a function that yields values one at a time, saving memory compared to storing all values in a list.

Creating a Generator Function

def count_up_to(n):
    count = 1
    while count <= n:
        yield count
        count += 1
gen = count_up_to(5)
print(next(gen))  # Output: 1
print(next(gen))  # Output: 2

Generators do not store values in memory; they generate values on demand.


4. Generator Expressions (Like List Comprehensions but Lazy)

Just like list comprehensions, but using parentheses () instead of brackets []

gen_exp = (x * 2 for x in range(5))
print(next(gen_exp))  # Output: 0
print(next(gen_exp))  # Output: 2

Saves memory, especially useful for large data sets.


5. Key Differences Between List Comprehensions and Generators

FeatureList ComprehensionGenerator
Syntax[expression for item in iterable](expression for item in iterable)
ExecutionStores all values in memoryGenerates values one at a time
PerformanceFaster for small datasetsMore memory-efficient for large datasets
Use caseWhen you need the whole list at onceWhen iterating over a large dataset

6. Summary

List comprehensions create lists efficiently in a single line.
Generators produce values lazily, saving memory.
Use list comprehensions when working with small datasets.
Use generators when dealing with large datasets or infinite sequences.