List Comprehension
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.
The basic syntax of a list comprehension is:
new_list = [expression for item in iterable if condition]
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]
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]
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 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)]
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)
List comprehensions can be nested to create more complex structures:
matrix = [[j for j in range(5)] for i in range(3)]
print(matrix)
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)