list unpack trick?

Alex Martelli aleaxit at yahoo.com
Sat Jan 22 09:50:36 CET 2005


Fredrik Lundh <fredrik at pythonware.com> wrote:
   ...
> or (readable):
> 
>     if len(list) < n:
>         list.extend((n - len(list)) * [item])

I find it just as readable without the redundant if guard -- just:

    alist.extend((n - len(alist)) * [item])

of course, this guard-less version depends on N*[x] being the empty list
when N<=0, but AFAIK that's always been the case in Python (and has
always struck me as a nicely intuitive semantics for that * operator).

itertools-lovers may prefer:

    alist.extend(itertools.repeat(item, n-len(alist)))

a bit less concise but nice in its own way (itertools.repeat gives an
empty iterator when its 2nd argument is <=0, of course).


Alex



More information about the Python-list mailing list