How does Python's list comprehension work?

Python's list comprehension provides a concise way to create lists. It consists of square brackets containing an expression followed by a `for` clause, then zero or more `for` or `if` clauses. 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.

Here's a breakdown of how list comprehension works in Python:

1. Basic syntax:


new_list = [expression for item in iterable]



2. Using a `for` loop:


numbers = [1, 2, 3, 4, 5]
squared_numbers = [num ** 2 for num in numbers]
# Output: [1, 4, 9, 16, 25]



3. Adding an `if` condition:


numbers = [1, 2, 3, 4, 5]
even_numbers = [num for num in numbers if num % 2 == 0]
# Output: [2, 4]



4. Nested list comprehension:


matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_matrix = [num for row in matrix for num in row]
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]



5. Using list comprehension with functions:


def square(x):
return x ** 2

numbers = [1, 2, 3, 4, 5]
squared_numbers = [square(num) for num in numbers]
# Output: [1, 4, 9, 16, 25]



List comprehensions are considered more Pythonic and efficient than traditional loops for creating lists, as they are more readable and concise.
How does Python's list comprehension work?

Related Questions