Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiom for flattening a shallow nested list: how does it work?

Tags:

python

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.)

like image 271
Matthew Scouten Avatar asked Sep 25 '12 15:09

Matthew Scouten


People also ask

How do you flatten a list of lists?

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] .

How do you flatten a shallow list in Python?

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.


1 Answers

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]
like image 200
DSM Avatar answered Nov 14 '22 21:11

DSM