List comprehension is a concise way to create lists in Python. It provides an elegant way of generating lists by applying an expression to each item in an iterable (like a list or range) without the need for a traditional for loop or append() method. It makes the code cleaner, more readable, and often more efficient.
Basic Syntax
The basic structure of list comprehension is:
[expression for item in iterable]
This syntax is equivalent to:
result = []
for item in iterable:
result.append(expression)
Example 1: Creating a List of Squares
Using list comprehension to generate a list of squares for numbers from 0 to 9:
squares = [x**2 for x in range(10)]
print(squares)
Output:
code[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Example 2: Filtering Items with Conditions
You can also add conditions to list comprehensions to filter items. For example, let’s create a list of even numbers from 0 to 9:
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
Output:
[0, 2, 4, 6, 8]
Example 3: Applying Functions in List Comprehension
You can apply a function to the items in the iterable. Let’s say we want to convert a list of strings to uppercase:
fruits = ['apple', 'banana', 'cherry']
upper_fruits = [fruit.upper() for fruit in fruits]
print(upper_fruits)
Output:
['APPLE', 'BANANA', 'CHERRY']
Example 4: Nested List Comprehensions
List comprehensions can be nested, allowing you to create lists of lists. For example, let’s create a 3×3 matrix:
pythonCopy codematrix = [[x for x in range(3)] for _ in range(3)]
print(matrix)
Output:
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
Example 5: Flattening a Nested List
If you have a list of lists and you want to flatten it into a single list, you can use a nested list comprehension:
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]
Summary
List comprehension is a highly efficient and Pythonic way to create and manipulate lists. It can simplify your code by reducing the need for multiple lines and loops, making it more readable and often more efficient. Whether you’re performing transformations, applying conditions, or generating lists from other lists, list comprehension is an essential tool in Python programming.