Simplifying Lists with List Comprehensions
List Comprehensions
allow you to create lists using for loops
and conditional statements
in a single line of code.
Structure of List Comprehensions
[expression for item in iterable]
Utilizing List Comprehensions
List comprehensions are written inside square brackets ([]
) with an expression, a for loop, and optionally an if condition.
This allows you to generate new lists based on existing iterables like lists or tuples.
Example of List Comprehension
numbers = [1, 2, 3, 4, 5]
squared = [num ** 2 for num in numbers]
print("squared:", squared)
# [1, 4, 9, 16, 25]
List comprehensions are used to apply operations to each item of an existing list to generate a new list, or to create a new list including only items that meet specific conditions.
List Comprehension with Condition
numbers = [1, 2, 3, 4, 5]
# Include only even numbers
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)
# [2, 4]
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.