Python : List Comprehensions
What is List Comprehensions in Python?
List comprehensions are a concise and powerful way to create lists in Python. They allow you to create a new list by applying an expression to each element of an existing list, with optional filtering based on a condition. This is done in a single line of code, making list comprehensions a favorite of many Python programmers.
The syntax of a list comprehension
new_list = [expression for item in iterable if condition]
Creating a Simple List Comprehension
Suppose we have a list of numbers and we want to create a new list that contains the square of each number in the original list. We can use a list comprehension to do this:
numbers = [1, 2, 3, 4, 5] squares = [x**2 for x in numbers] print(squares) #Output : [1, 4, 9, 16, 25]
Adding a Condition to a List Comprehension
Now suppose we want to create a new list that only contains the squares of the odd numbers in the original list. We can add a condition to the list comprehension to do this:
numbers = [1, 2, 3, 4, 5] squares = [x**2 for x in numbers if x % 2 == 1] print(squares) # output : [1, 9, 25]
Nested List Comprehensions
List comprehensions can also be nested, allowing you to create more complex data structures.
For example, suppose we have a matrix represented as a list of lists and we want to create a new list containing the diagonal elements of the matrix.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] diagonal = [matrix[i][i] for i in range(len(matrix))] print(diagonal) # output : [1, 5, 9]
- List comprehensions are a powerful and concise way to create new lists in Python. They allow you to apply an expression to each element of an existing list and filter the results based on a condition, all in a single line of code.