unpack sequence to tuple?

Alex Martelli aleaxit at yahoo.com
Tue Jan 23 16:05:51 EST 2001


"John Nielsen" <nielsenjf at my-deja.com> wrote in message
news:94kf4n$58u$1 at nnrp1.deja.com...
    [snip]
> > Unfortunately, tuples and lists cannot be concatenated, which
> > is why we need to cast the sequence into a definite form here --
> > choosing list would of course work just as well:
> >
> > def padSequence(seq, length):
> >     return (list(seq)+[None]*length)[:length]
>
> Or you could just use extend. which may be a little clearer.
>
> def padSequence(seq, length):
>     a=list(seq)
>     a.extend(list((None,)*length))
>     return a[:length]

Clarity, I guess, is in the eye of the beholder; even if I
did decide to split this simple function into three statements,
they'd likely be:

def padSequence(seq, length):
    temp = list(seq)
    temp += [None]*length
    return temp[:length]

at least the [None]*length is clearly simply than starting
from the (None,)*length tuple then casting it to a list (not
that you NEED the cast, if .extend is what you want to
use -- .extend can be called with any sequence).

But if one does decide to split it up into multiple statements,
then it may be worth distinguishing the cases of too-long
and too-short sequences; the 'homogeneization' into
"always too long" which I get by appending length copies
of None has the specific purpose of letting a single
expression work without conditionals (which are not
clear nor comfortable in expressions, though the can
often be built up from and and or applications).

def padSequence(seq, length):
    if len(seq)>=length: return seq[:length]
    return list(seq)+[None]*(length-len(seq))

This is probably the first thing that will come to mind
to a newbie, after all, and thus might be simplest for
said newbie to understand.


Alex






More information about the Python-list mailing list