Category: python
Python List Comprehensions
Published on 24 Jul 2026
Explanation
A list comprehension is a concise and efficient way to create a new list from an existing iterable such as
Code:
# Create a list of squares numbers = [1, 2, 3, 4, 5] squares = [num * num for num in numbers] print(squares) # Create a list of cubes cubes = [num ** 3 for num in numbers] print(cubes)
Explanation
List comprehensions can include conditional statements to filter elements while creating a new list. The condition is placed after the
Code:
numbers = list(range(1, 21)) # Even numbers even_numbers = [num for num in numbers if num % 2 == 0] print(even_numbers) # Odd numbers odd_numbers = [num for num in numbers if num % 2 != 0] print(odd_numbers) # Numbers greater than 10 greater_than_ten = [num for num in numbers if num > 10] print(greater_than_ten)
Explanation
A dictionary comprehension is a concise way to create dictionaries. It follows the syntax {key_expression: value_expression for item in iterable}.
Code:
numbers = [1, 2, 3, 4, 5]
# Number and its square
square_dict = {num: num * num for num in numbers}
print(square_dict)
# Number and cube
cube_dict = {num: num ** 3 for num in numbers}
print(cube_dict)
# Filter even numbers
even_square = {num: num * num for num in numbers if num % 2 == 0}
print(even_square)
Explanation
A set comprehension creates a set from an iterable using a concise syntax similar to list comprehensions. Since sets automatically
Code:
numbers = [1, 2, 2, 3, 4, 4, 5, 5]
# Remove duplicates
unique_numbers = {num for num in numbers}
print(unique_numbers)
# Square values
square_set = {num * num for num in numbers}
print(square_set)
# Even numbers
even_set = {num for num in numbers if num % 2 == 0}
print(even_set)
Explanation
Comprehensions are widely used in real-world Python applications because they simplify data transformation tasks. List comprehensions are useful for processing
Code:
students = [
{'name': 'John', 'marks': 85},
{'name': 'Alice', 'marks': 92},
{'name': 'David', 'marks': 78}
]
# List of student names
names = [student['name'] for student in students]
print(names)
# Dictionary of student marks
marks = {student['name']: student['marks'] for student in students}
print(marks)
# Set of grades
grades = {('A' if student['marks'] >= 90 else 'B') for student in students}
print(grades)