Python Documentation

List Comprehension

List Comprehension in Python

List comprehension is a concise and powerful way to create lists in Python. It provides a more readable and often faster alternative to using loops and append() method.

Basic Syntax

The basic syntax of a list comprehension is:

new_list = [expression for item in iterable if condition]

Simple Example

Let's create a list of squares of 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]

List Comprehension with Condition

We can add a condition to filter items:

even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # Output: [0, 4, 16, 36, 64]

Nested List Comprehension

List comprehensions can be nested:

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

List Comprehension vs. Traditional Loop

List comprehension is often more concise than traditional loops:

# Traditional loop
squares = []
for x in range(10):
ㅤㅤsquares.append(x**2)

# List comprehension
squares = [x**2 for x in range(10)]

Using Multiple If Conditions

You can use multiple conditions in a list comprehension:

numbers = [x for x in range(100) if x % 2 == 0 if x % 5 == 0]
print(numbers)

Nested List Comprehensions

List comprehensions can be nested to create more complex structures:

matrix = [[j for j in range(5)] for i in range(3)]
print(matrix)

List Comprehension with Functions

You can use functions in list comprehensions:

def is_even(n):
ㅤㅤreturn n % 2 == 0

even_numbers = [x for x in range(20) if is_even(x)]
print(even_numbers)