![]() |
VOOZH | about |
List Comprehension are one of the most amazing features of Python. It is a smart and concise way of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops.
new_list = [[expr for item in inner_iterable] for item in outer_iterable]
Parameters:
Let's look at some of the examples:
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
Explanation: This code builds a 5x5 matrix (list of lists), where each row contains numbers from 0 to 4 using nested loops.
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
Explanation: A more concise version of the same logic, the inner loop [c for c in range(5)] creates each row and the outer loop repeats it 5 times.
[1, 3, 5, 7, 9]
Explanation: This loops through a 2D list and adds all odd numbers to a new list odds.
[1, 3, 5, 7, 9]
Explanation: This single line does the same thing, it goes through each row 'r', each element 'e' and includes 'e' only if it's odd.
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Explanation: This code flattens a nested list m by iterating over each sublist and adding every value to flat.
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Explanation: A more compact version that loops through every sublist r and each value v and collects all values into a flat list.
[['Apple', 'Banana', 'Cherry'], ['Date', 'Fig', 'Grape'], ['Kiwi', 'Lemon', 'Mango']]
Explanation: Each string (fruit name) in the nested list is capitalized using nested loops.
[['Apple', 'Banana', 'Cherry'], ['Date', 'Fig', 'Grape'], ['Kiwi', 'Lemon', 'Mango']]
Explanation: Each fruit f in every row r is capitalized using .capitalize() and the modified rows are collected into mod_m.