List comprehensions are a concise and efficient way to create lists in Python. They allow you to transform, filter, and combine data in a single, readable line of code.
Instead of using traditional for loops and if statements, list comprehensions provide a more compact and expressive syntax. Here’s a simple example of a list comprehension that squares each number in a list:
numbers = [1, 2, 3, 4, 5]
squared_numbers = [num ** 2 for num in numbers]
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
In this example, the list comprehension [num ** 2 for num in numbers]
creates a new list where each number in the numbers
list is squared. List comprehensions can also include conditional logic, allowing you to filter elements based on certain criteria:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) # Output: [2, 4, 6, 8, 10]