[Python-ideas] Generator unpacking

Jonathan Goble jcgoble3 at gmail.com
Mon Feb 15 13:00:27 EST 2016


On Mon, Feb 15, 2016 at 12:53 PM, Sven R. Kunze <srkunze at mail.de> wrote:
> On 15.02.2016 18:39, Ethan Furman wrote:
>>
>> I /think/ I've used that trick to confirm an iterable was empty; I /know/
>> I've used
>>
>> [some_var] = some_var
>
>
> Is that an unknown Python idiom?
>
> It looks short but still insane.

It's actually a useful way to quickly unpack nested lists and tuples.
Here's a quick example:

>>> x = []
>>> x.append((1, 2))
>>> x.append(3)
>>> x.append((4, 5))
>>> x.append([6, 7, 8])
>>> x
[(1, 2), 3, (4, 5), [6, 7, 8]]
>>> [(a, b), c, (d, e), [f, g, h]] = x
>>> a
1
>>> b
2
>>> c
3
>>> d
4
>>> e
5
>>> f
6
>>> g
7
>>> h
8


More information about the Python-ideas mailing list