Member-only story
List comprehensions are a staple feature of Python that can make your code more readable, concise, and efficient. They allow you to create new lists by applying operations to existing lists, making them a powerful tool for data manipulation and transformation.
Let’s start with a simple example. Suppose you have a list of numbers, and you want to create a new list containing only the even numbers. Without list comprehensions, you would typically use a for
loop and an if
statement:
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []
for num in original_list:
if num % 2 == 0:
even_numbers.append(num)
print(even_numbers) # Output: [2, 4, 6, 8, 10]
With list comprehensions, you can accomplish the same task in a single line:
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in original_list if num % 2 == 0]
print(even_numbers) # Output: [2, 4, 6, 8, 10]
The basic syntax for a list comprehension is:
new_list = [expression for item in iterable if condition]