Best idiom to unpack a variable-size sequence

George Sakkis george.sakkis at gmail.com
Tue Dec 18 13:13:13 EST 2007


On Dec 18, 12:49 pm, ram <rickmorri... at gmail.com> wrote:
> Here's a little issue I run into more than I like: I often need to
> unpack a sequence that may be too short or too long into a fixed-size
> set of items:
>
> a, b, c = seq      # when seq = (1, 2, 3, 4, ...) or seq = (1, 2)
>
> What I usually do is something like this:
>
>      a, b, c = (list(seq) + [None, None, None])[:3]
>
> but that just feels rather ugly to me -- is there a good Pythonic
> idiom for this?

In terms of brevity I don't think so; however it can be done more
efficient and general (e.g. for infinite series) using itertools:

from itertools import islice, chain, repeat

def unpack(iterable, n, default=None):
    return islice(chain(iterable,repeat(default)), n)

a, b, c = unpack(seq, 3)

George



More information about the Python-list mailing list