What is List Comprehension?
List comprehension is a concise way to create lists in Python. It allows you to generate a new list by applying an expression to each item in an existing iterable (like a list, tuple, or range). The syntax is straightforward:
[expression for item in iterable if condition]`
- expression: The value or operation applied to each item.
- item: The variable representing each element in the iterable.
- iterable: The collection of items you are iterating over (e.g., a list or range).
- condition (optional): A filtering condition to include only certain items.
Simple Examples of List Comprehension
Example 1: Creating a List of Numbers
Let’s start with something simple: creating a list of numbers from 0 to 9.
numbers = [x for x in range(10)]
print(numbers)`
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`
Here, x for x in range(10) generates each number in the range, and the list comprehension collects them into a list.
Example 2: Squaring Numbers
Now, let’s create a list of squared numbers from 0 to 9.
squares = [x**2 for x in range(10)]
print(squares)`
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In this case, the expression x**2 calculates the square of each number, and the list comprehension stores the results in a new list.
Example 3: Filtering Even Numbers
What if we only want the even numbers from 0 to 9? We can add a condition to our list comprehension.
evens = [x for x in range(10) if x % 2 == 0]
print(evens)`
Output:
[0, 2, 4, 6, 8]
The condition if x % 2 == 0 filters out the odd numbers, leaving only the even ones.
More Complex Examples of List Comprehension
Now that you’ve got the basics down, let’s look at some more advanced uses of list comprehension.
Example 4: Nested Loops
You can use list comprehension with nested loops to create combinations of items. For example, let’s create a list of coordinate pairs (x, y) where x is from 0 to 2 and y is from 0 to 2.
python
Copy code
coordinates = [(x, y) for x in range(3) for y in range(3)]
print(coordinates)
Output:
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
Here, the list comprehension iterates over x and y, producing every possible combination of (x, y).
Example 5: Flattening a List of Lists
Suppose you have a list of lists, and you want to flatten it into a single list. List comprehension makes this easy.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
The list comprehension iterates over each row in matrix, and then over each number in the row, collecting all the numbers into a single list.
Example 6: Conditional Expressions
You can also use conditional expressions within list comprehension to apply different operations based on a condition.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_or_doubled = [x**2 if x % 2 == 0 else x*2 for x in numbers]
print(squared_or_doubled)
Output:
[2, 4, 6, 16, 10, 36, 14, 64, 18, 100]
Here, even numbers are squared, and odd numbers are doubled. The expression x**2 if x % 2 == 0 else x*2 is applied to each number in the list.
Example 7: Using Functions in List Comprehension
Finally, let’s see how you can incorporate functions into list comprehension. Suppose you want to create a list of factorials for numbers from 1 to 5.
import math
factorials = [math.factorial(x) for x in range(1, 6)]
print(factorials)
Output:
[1, 2, 6, 24, 120]
Here, math.factorial(x) computes the factorial of each number, and the results are stored in a new list.
Why Use List Comprehension?
- Conciseness: List comprehension reduces the amount of code you need to write, making your code more readable.
- Performance: In many cases, list comprehension can be faster than using traditional loops, as it’s optimized for creating lists.
- Readability: Once you’re familiar with the syntax, list comprehension can make your code easier to understand at a glance.
Conclusion
List comprehension is a powerful tool in Python that allows you to create lists in a clean and efficient way. By mastering the basics and exploring more complex examples, you’ll be able to write Python code that’s not only functional but also elegant.
Whether you’re generating a simple list of numbers or flattening a complex data structure, list comprehension can help you achieve your goals with fewer lines of code. So, don’t be afraid to experiment with different expressions and conditions—you’ll soon see just how versatile this feature can be.
Happy coding!
Related Topics
Related Resources
The Ultimate AI Learning Roadmap for Software Engineers (2025 Edition)
The line between 'software engineer' and 'AI engineer' is disappearing. Are you prepared for the shift from deterministic coding to orchestrating intelligent, probabilistic systems? This comprehensive AI learning roadmap is designed specifically for software professionals. It's a practical, timeline based guide to not only learn the necessary skills but also leverage your existing engineering expertise to transition into a high impact AI role, covering everything from mathematical foundations to production grade MLOps and Generative AI.
articleBuild AI Agents from Scratch with Python and Gemini: A Beginner Friendly Guide to Use Cases and Challenges
AI agents are moving beyond simple chatbots, and with Python and Gemini, beginners can now start building useful autonomous workflows faster than ever. This article introduces AI agents in a practical, beginner friendly way and shows how Python and Gemini can be used to create them from scratch. It covers the core building blocks, a simple development path, real world use cases, and the main challenges to watch for when getting started.
articleDesign Patterns in Python
Learn how to implement design patterns in Python