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 should be something I missed:
>>> N = 5
>>> a = [1]
>>> map(lambda x, y: y if x is None else x, a, ['']*N)
[1, '', '', '', '']
I think this approach is more visual and pythonic.
more-itertools
is a library that includes a specialpadded
tool for this kind of problem:Alternatively,
more_itertools
also implements Python itertools recipes includingpadnone
andtake
as mentioned by @kennytm, so they don't have to be reimplemented:If you wish to replace the default
None
padding, use a list comprehension:gnibbler's answer is nicer, but if you need a builtin, you could use
itertools.izip_longest
(zip_longest
in Py3k):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: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
andtake
recipes)Usage:
You could also use a simple generator without any build ins. But I would not pad the list, but let the application logic deal with an empty list.
Anyhow, iterator without buildins
or if you don't want to change
a
in placeyou can always create a subclass of list and call the method whatever you please