[Python-ideas] Boundaries for unpacking

Michel Desmoulin desmoulinmichel at gmail.com
Fri Apr 8 10:15:10 EDT 2016

Le 07/04/2016 21:18, Terry Reedy a écrit :
> On 4/7/2016 1:03 PM, Michel Desmoulin wrote:
>> Python is a lot about iteration, and I often have to get values from an
>> iterable. For this, unpacking is fantastic:
>> a, b, c = iterable
>> One that problem arises is that you don't know when iterable will
>> contain 3 items.
> You need to augment if needed to get at least 3 items.
> You need to chop if needed to get at most 3 items.  The following does
> exactly this.
> import itertools as it
> a, b, c = it.islice(it.chain(iterable, it.repeat(default, 3), 3)
> You can wrap this if you want with def exactly(iterable, n, default).
> This might already be a recipe in the itertools doc recipe section.

Yes and you can also do that for regular slicing on list. But you don't,
because you have regular slicing, which is cleaner, and easier to read
and remember.

This is not only hard to remember, but needs a comment. And an import.

More information about the Python-ideas mailing list