Quantcast
Channel: RasadaCrea rss feeds aggregator
Viewing all articles
Browse latest Browse all 176

Python, how to flatten a list of lists with a list comprehension

$
0
0
By Vasudev Ram Recently, I saw this comment thread on Hacker News: Python Language Features and Tricks (sahandsaba.com) , which was about this post: 30 Python Language Features and Tricks You May Not Know About One of the comments on the HN thread was this : Except from it: "I don't understand how this one to flatten lists works: a = , 2], , 4], , 6]] for l in a for x in l] Can somebody explain what the order of operations is here and what the variables refer to in the various stages of evaluation?" Another HN user answered the question, and I also commented on it. But the interesting part was where another user posted below, in the same thread, this comment: "So that flattening can also be written as: x = ,2], ,4], ,6]] for x in x for x in x] " The interesting part here (to me) was not just the use of a list comprehension to flatten the list, but the fact that the same variable is used throughout the list comprehension; in fact it is used 5 times in the expression. I tried it out, and it works. Then I thought of checking whether the same kind of code would work for a triply-nested list, and found that it did work: Flatten a list that is nested to three levels with a list comprehension. x = ,2], ,4]], ,6], ,8]]] print "before flatten, .. cntd

Viewing all articles
Browse latest Browse all 176

Trending Articles