Member-only story
Understanding List Comprehensions in Python
2 min readJul 11, 2024
List comprehensions are a concise way to create lists in Python. They provide a more readable and efficient way to generate lists compared to traditional loops.
What is a List Comprehension?
A list comprehension is a syntactic construct that allows you to create a new list by applying an expression to each item in an existing iterable (like a list or range).
Basic Syntax
new_list = [expression for item in iterable if condition]
expression
is the value to add to the new list.item
is the variable representing each element in the iterable.iterable
is the collection of items to loop through.condition
is an optional filter that determines which items are included.
Examples
Creating a List of Squares
squares = [x**2 for x in range(10)]
print(squares)
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Filtering with a Condition
evens = [x for x in range(20) if x % 2 == 0]
print(evens)
# Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]