List comprehensions are a concise way to create lists in Python. They provide a concise way to create lists based on existing lists, and are often more readable and efficient than using loops.
Basic Syntax
List comprehensions have the following basic syntax:
[expression for item in iterable]
expression
: The expression that will be evaluated and added to the list for each item in the iterable.item
: The variable representing each item in the iterable.iterable
: The sequence of items to iterate over.
Example
Suppose you have a list of numbers, and you want to create a new list that contains only the even numbers. You can use a list comprehension to achieve this:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
The even_numbers
list will contain [2, 4, 6, 8, 10]
.
Advanced Features
List comprehensions also support several advanced features, such as:
- Conditional expressions: You can use conditional expressions to include or exclude items based on certain conditions.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
odd_numbers = [num for num in numbers if num % 2 != 0]
- Nested comprehensions: You can use nested comprehensions to create lists of lists or other complex data structures.
matrix = [[i, j] for i in range(5) for j in range(5)]
The matrix
will be a list of lists, where each inner list contains pairs of numbers from 0 to 4.
Further Reading
For more information on list comprehensions, you can refer to the following resources:
[center]