I found this bit of code in a module I am working on:
l = opaque_function()
thingys = [x for y in l for x in y]
I can't read this. By experiment, I was able to determe that it is flattening a 2-level nested list, but the syntex is still opaque to me. It has obviously omitted some optional brackets.
>>> l = [[1,2],[3,4]]
>>> [x for y in l for x in y]
[1, 2, 3, 4]
My eyes want to parse it as either: [x for y in [l for x in y] ]
or [ [x for y in l] for x in y ]
, but both of those fail due to y
not being defined.
How should I be reading this?
(I suspect I will feel very embarassed when this is explained.)
Flattening a list of lists entails converting a 2D list into a 1D list by un-nesting each list item stored in the list of lists - i.e., converting [[1, 2, 3], [4, 5, 6], [7, 8, 9]] into [1, 2, 3, 4, 5, 6, 7, 8, 9] .
A simple and straightforward solution is to append items from sublists in a flat list using two nested for loops. A more compact and Pythonic solution is to use chain() function from itertools module.
This used to really confuse me. You should read it like a nested loop:
new_list = []
for y in l:
for x in y:
new_list.append(x)
becomes
for y in l for x in y [do] new_list.append(x)
becomes
[x for y in l for x in y]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With