Creating Lists Concisely Using List Comprehension
List Comprehension is a unique Python syntax that allows you to create lists concisely.
You can express loops and conditionals in a single line, which enhances code readability and reduces writing time.
How to Use List Comprehension
The basic structure of list comprehension is as follows:
[expression for item in iterable]
-
expression
: The expression to be used in the loop -
item
: The variable to be used in the loop -
iterable
: The object to be iterated over
By using this structure, you can create a squared list much more concisely compared to traditional loops.
Examples of List Comprehension
# Create an iterable list
numbers = [1, 2, 3, 4, 5]
# Create a squared list using list comprehension
squared_numbers = [number ** 2 for number in numbers]
# Prints [1, 4, 9, 16, 25]
print(squared_numbers)
List comprehension can also include conditionals.
You can add conditionals at the end of the list comprehension to include only elements that satisfy the condition.
# Create a list with only even numbers squared
numbers = [1, 2, 3, 4, 5]
# Store the squares of even elements only in the even_squared list
even_squared = [number ** 2 for number in numbers if number % 2 == 0]
# Prints [4, 16]
print(even_squared)
This code filters out even elements from the list numbers
, squares them, and stores them in the even_squared
list.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.