Nested List Comprehensions
Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops. Below is the program which implements nested loop:
Python
matrix = [] for i in range ( 3 ): # Append an empty sublist inside the list matrix.append([]) for j in range ( 5 ): matrix[i].append(j) print (matrix) |
Output
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
Now by using nested list comprehensions, the same output can be generated in fewer lines of code.
Python
# Nested list comprehension matrix = [[j for j in range ( 5 )] for i in range ( 3 )] print (matrix) |
Output
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
Python – List Comprehension
A Python list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list.
Example:
Python
numbers = [ 12 , 13 , 14 ,] doubled = [x * 2 for x in numbers] print (doubled) |
Output
[24, 26, 28]