I have a list of size < N and I want to pad it up to the size N with a value.
Certainly, I can use something like the following, but I feel that there sh
If you want to pad with None instead of '', map() does the job:
>>> map(None,[1,2,3],xrange(7))
[(1, 0), (2, 1), (3, 2), (None, 3), (None, 4), (None, 5), (None, 6)]
>>> zip(*map(None,[1,2,3],xrange(7)))[0]
(1, 2, 3, None, None, None, None)
gnibbler's answer is nicer, but if you need a builtin, you could use itertools.izip_longest (zip_longest
in Py3k):
itertools.izip_longest( xrange( N ), list )
which will return a list of tuples ( i, list[ i ] )
filled-in to None. If you need to get rid of the counter, do something like:
map( itertools.itemgetter( 1 ), itertools.izip_longest( xrange( N ), list ) )
To go off of kennytm:
def pad(l, size, padding):
return l + [padding] * abs((len(l)-size))
>>> l = [1,2,3]
>>> pad(l, 7, 0)
[1, 2, 3, 0, 0, 0, 0]
There is no built-in function for this. But you could compose the built-ins for your task (or anything :p).
(Modified from itertool's padnone
and take
recipes)
from itertools import chain, repeat, islice
def pad_infinite(iterable, padding=None):
return chain(iterable, repeat(padding))
def pad(iterable, size, padding=None):
return islice(pad_infinite(iterable, padding), size)
Usage:
>>> list(pad([1,2,3], 7, ''))
[1, 2, 3, '', '', '', '']