Member-only story
List comprehensions are a powerful feature in Python that allow you to create lists in a concise and expressive way. They can make your code more readable and easier to maintain, especially when working with lists and sequences. Let’s dive into some examples and see how they can enhance your Python skills.
Basic List Comprehension
Suppose you want to create a list of squared numbers from a list of numbers. Instead of using a traditional for loop:
numbers = [1, 2, 3, 4, 5]
squared_numbers = []
for num in numbers:
squared_numbers.append(num ** 2)
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
You can use a list comprehension to achieve the same result in a single line:
numbers = [1, 2, 3, 4, 5]
squared_numbers = [num ** 2 for num in numbers]
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
The list comprehension [num ** 2 for num in numbers]
creates a new list by squaring each number in the numbers
list.