List Comprehensions
What is List Comprehension?
List comprehension is a short and clean way to create a new list from an existing collection.
Normally, we create a list using:
- An empty list
- A loop
- A condition or calculation
append()
List comprehension combines these steps into one readable line.
Traditional Loop vs List Comprehension
kids = ["Jaswitha", "dhanvik", "Divisha", "Kavya", "Rohansh"]
# Traditional way
chocolates = []
for kid in kids:
chocolates.append(kid + " Gets a chocolate")
print(chocolates)
# List Comprehension
chocolates = [kid + " Gets a chocolate" for kid in kids]
print(chocolates)
Basic Syntax
new_list = [expression for item in collection]
- collection → The existing list, tuple, string, range, set or other iterable
- item → Each individual value taken from the collection
- expression → What should be stored in the new list
numbers = [1, 2, 3, 45]
squares = [number**2 for number in numbers]
print(squares)
List Comprehension with range()
You don't always need an existing list. You can use range().
[number for number in range(1, 6)]
# squares from 1 to 10
[number**2 for number in range(1, 11)]
# cubes from 1 to 5
[number**3 for number in range(1, 6)]
List Comprehension with Strings
A string is also iterable. Python can process one character at a time.
word = "PYTHON"
[character for character in word]
# convert every character to lowercase
[character.lower() for character in word]
names = ["kencha", "mohan", "manu", "Prashant"]
[name.upper() for name in names]
List Comprehension with Condition
Sometimes we do not want to process every value. We only want values that satisfy a condition.
[expression for item in collection if condition]
numbers = [1, 2, 3, 4, 5, 6]
# select even numbers
[number for number in numbers if number % 2 == 0]
# select odd numbers
[number for number in numbers if number % 2 != 0]
marks = [34, 67, 89, 45, 76, 23]
[mark for mark in marks if mark > 50]
List Comprehension with if-else
There is an important difference:
if→ used for filteringif-else→ used for transforming every value
[value_if_true if condition else value_if_false for item in collection]
numbers = [1, 2, 3, 4, 5]
["even" if number % 2 == 0 else "Odd" for number in numbers]
marks = [78, 24, 56, 31, 90]
["pass" if mark >= 35 else "fail" for mark in marks]
Multiple Conditions
numbers = range(1, 31)
# divisible by both 2 and 3
[number for number in numbers if number % 2 == 0 and number % 3 == 0]
# divisible by 2 or 3
[number for number in numbers if number % 2 == 0 or number % 3 == 0]
marks = [34, 55, 67, 82, 76, 91, 49]
[mark for mark in marks if 50 <= mark <= 80]
Practical Data Examples
names = ["Arjun", "Ravi", "Anjali", "Meena", "Amit"]
# names starting with A
[name for name in names if name.startswith("A")]
# names longer than 4 characters
[name for name in names if len(name) > 4]
# cleaning text data
names = [" Ravi", "Sita ", " John "]
[name.strip() for name in names]
# convert string numbers to integers
numbers_as_text = ["10", "20", "30", "40"]
[int(value) for value in numbers_as_text]
Nested List Comprehensions
A nested list comprehension contains more than one for.
# Traditional nested loops
results = []
for row in range(1, 4):
for column in range(1, 4):
results.append((row, column))
# Nested List Comprehension
[(row, column) for row in range(1, 4) for column in range(1, 4)]
colors = ["Red", "Blue", "Black"]
sizes = ["M", "L"]
[(color, size) for color in colors for size in sizes]
# Flatten a matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[number for row in matrix for number in row]
Calling Functions inside List Comprehension
def calculate_square(number):
return number**2
numbers = [1, 2, 3, 4, 5]
[calculate_square(number) for number in numbers]
def calculate_grade(mark):
if mark >= 75:
return "Distinction"
elif mark >= 60:
return "First class"
elif mark >= 35:
return "Pass"
else:
return "Fail"
marks = [82, 65, 42, 23]
grade = [calculate_grade(mark) for mark in marks]
print(grade)
List Comprehension with enumerate() and zip()
students = ["Mohan", "Manohar", "Manu"]
numbered_students = [
f"{index}.{name}"
for index, name in enumerate(students, start=1)
]
print(numbered_students)
names = ["ravi", "sita", "john"]
marks = [78, 92, 65]
result = [
f"{name} scored {mark}"
for name, mark in zip(names, marks)
]
print(result)
Advantages of List Comprehension
- Shorter code
- Easier to read
- Avoids repeated
append() - Faster for simple operations
- Useful for data cleaning:
- Converting data types
- Cleaning strings
- Filtering records
- Applying calculations
- Creating labels
Disadvantage
Difficult to read when too complex.
List Comprehensions
Master the short and clean way to create lists in Python.
Select any topic from the left sidebar to begin.
Start Learning →
