Python provides efficient ways to handle collections of data using list comprehensions and generators.
Let's explore both in detail!
List comprehension provides a compact way to generate a new list from an existing sequence.
new_list = [expression for item in iterable if condition]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!
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
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
A generator is a function that yields values one at a time, saving memory compared to storing all values in a list.
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: 2Generators do not store values in memory; they generate values on demand.
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: 2Saves memory, especially useful for large data sets.
| Feature | List Comprehension | Generator |
|---|---|---|
| Syntax | [expression for item in iterable] | (expression for item in iterable) |
| Execution | Stores all values in memory | Generates values one at a time |
| Performance | Faster for small datasets | More memory-efficient for large datasets |
| Use case | When you need the whole list at once | When iterating over a large dataset |
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.
Sign in to join the discussion and post comments.
Sign inPython for Web Development
Python for Web Development is a comprehensive tutorial series covering the fundamentals of building web applications using Flask and Django. From setting up a project to working with databases, authentication, REST APIs, and deployment on cloud platforms, this series provides a solid foundation for developing secure and scalable web applications.
Object-Oriented Programming (OOP) in Python
Learn the fundamentals of Object-Oriented Programming (OOP) in Python, including classes, objects, inheritance, polymorphism, encapsulation, and more. Understand how OOP enhances code reusability, scalability, and organization.