I am going through David Kopec's Classic Computer Science Problems in Python and in chapter 3 - came across this list comprehension.
all_locations = [locs for values in assignment.values() for locs in values]
I am unable to understand how exactly this list comprehension works.
From this answer for 'Double iteration in List' - it looks like I could change the names of the variables in the 2nd part of the list comprehension but that just breaks it.
Double Iteration in List Comprehension
I wanted to understand which is the first item that is getting iterated over and which is the next. The end result is a compacted list but am scratching my head over - how ??
This is the sample code I tried
class GridLocation(NamedTuple):
row: int
column: int
gl_1 = GridLocation(1, 1)
gl_2 = GridLocation(2, 2)
gl_3 = GridLocation(3, 3)
test = {'1' : [[gl_1, gl_2]], '2' : [[gl_2, gl_3]], '3': [[gl_3, gl_1]]}
print('test.values() -> ', test.values())
print('-' * 25 )
test_list_comp = [locs for values in test.values() for locs in values]
print('test_list_comp -> ', test_list_comp)
This is the result -
test.values() -> dict_values([
[[GridLocation(row=1, column=1), GridLocation(row=2, column=2)]],
[[GridLocation(row=2, column=2), GridLocation(row=3, column=3)]],
[[GridLocation(row=3, column=3), GridLocation(row=1, column=1)]]
])
-------------------------
test_list_comp -> [
[GridLocation(row=1, column=1), GridLocation(row=2, column=2)],
[GridLocation(row=2, column=2), GridLocation(row=3, column=3)],
[GridLocation(row=3, column=3), GridLocation(row=1, column=1)]
]