Best idiom to unpack a variable-size sequence

R

ram

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?

Thx,
Rick
 
G

George Sakkis

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
 
D

Duncan Booth

ram said:
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?

Pythonic might be to be explicit: i.e. know in advance how long the
sequence actually is.

One drawback I see with your code is that it doesn't give you any way to
specify different defaults for the values. So here's an alternative to
consider: try passing your sequence to a function. This lets you specify
appropriate defaults, and it reads quite cleanly. Of course it also forces
you to extract the code using those variables out into a separate function,
but that may not be a bad thing.
print a, b, c

 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top