Lesson 18 of 21 · 2 min
List Comprehensions — Elegant One-Line Loops
The WHY — Why List Comprehensions?
A very common pattern in Python is: create a new list by processing each item in an existing list. List comprehensions let you do this in one clean, readable line instead of 3-4 lines.
From for Loop to List Comprehension
# TRADITIONAL WAY — using a for loop:
squares = [] # start with empty list
for i in range(1, 6): # loop through 1, 2, 3, 4, 5
squares.append(i ** 2) # add the square of each number
print(squares) # display the result
# LIST COMPREHENSION WAY — same result in one line:
squares = [i ** 2 for i in range(1, 6)] # generate a list of squares
print(squares) # display the same result
Output: [1, 4, 9, 16, 25] [1, 4, 9, 16, 25]
List Comprehension with a Filter Condition
# Get only even numbers from 1 to 20: evens = [i for i in range(1, 21) if i % 2 == 0] # include only if i is even print(evens) # display the even numbers # Get names longer than 4 characters: names = ["Priya", "Ahmed", "Ravi", "Sara", "Arjun", "Meera"] long_names = [name for name in names if len(name) > 4] # filter by length print(long_names) # display names that passed the filter
Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] ['Priya', 'Ahmed', 'Arjun', 'Meera']
List Comprehension Structure
[expression for item in sequence if condition]
↑ ↑ ↑ ↑
What to add Each item What to Only include
to the list is called loop over items where this is TrueThe if condition part is optional — leave it out to include all items.
