new_list = [expression for item in iterable if condition]
new_list: The new list will be created using list comprehension.
expression: The expression or transformation to be applied to each item in the iterable.
item: It represents each individual item in the iterable that is being processed.
iterable: A sequence or collection of elements (e.g., list, tuple, string) that is being iterated over.
if condition(optional): It allows you to include a conditional statement to filter the items based on a certain condition. Only the items that satisfy the condition will be included in the new list.
A few examples of using list comprehension in practice, in order from basic to advanced.
Creating a list of squared numbers
This example generates a list of squared numbers from a list of integers:
numbers = [1, 2, 3, 4, 5, 6, 7, 2023] squared_numbers = [number ** 2 for number in numbers] print(squared_numbers)
[1, 4, 9, 16, 25, 36, 49, 4092529]
Filtering a list by a condition
This example creates a list of numbers that are dividable by 3 (greater than 1 and less than 20):
nums = [num for num in range(1, 20) if num % 3 == 0] print(nums)
[3, 6, 9, 12, 15, 18]
Creating a complex list
This example uses list comprehension syntax to create a list of tuples containing numbers and their squares:
numbers = [1, 2, 3, 4, 5] squared_tuples = [(num, num ** 2) for num in numbers] print(squared_tuples)
[(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
In this example, we’ll build a list of uppercase characters (excluding whitespace) from a given string:
string = "Sling Academy" uppercase_chars = [char.upper() for char in string if not char.isspace()] print(uppercase_chars)
['S', 'L', 'I', 'N', 'G', 'A', 'C', 'A', 'D', 'E', 'M', 'Y']