[Python-ideas] Boundaries for unpacking

Terry Reedy tjreedy at udel.edu
Thu Apr 7 15:18:59 EDT 2016


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.

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list