Any quicker way to flatten a list of pairs?

lt = [1,2,3]
z = [[w**2, w**3] for w in lt] 
[x for y in z for x in y]

Then I get

[1, 1, 4, 8, 9, 27]

To get the result, I write two line. Is there any way to shorten the code to one line to obtain the same result, like:

[w**2, w**3, for w in lt]  

??

Your two-line code is beautifully readable, but if you are playing code golf and need to cram everything into one line to save a few characters, you can write the ugly code:

[x for y in [[w**2, w**3] for w in lt] for x in y]

See also this proposal here:

https://mail.python.org/archives/list/python-ideas@python.org/message/7G732VMDWCRMWM4PKRG6ZMUKH7SUC7SH/

although unfortunately it doesn’t exist yet.

1 Like