list unpack trick?

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

Fredrik Lundh <fredrik at> 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).


More information about the Python-list mailing list