Some built-in to pad a list in python Some built-in to pad a list in python python python

Some built-in to pad a list in python


a += [''] * (N - len(a))

or if you don't want to change a in place

new_a = a + [''] * (N - len(a))

you can always create a subclass of list and call the method whatever you please

class MyList(list):    def ljust(self, n, fillvalue=''):        return self + [fillvalue] * (n - len(self))a = MyList(['1'])b = a.ljust(5, '')


I think this approach is more visual and pythonic.

a = (a + N * [''])[:N]


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, islicedef 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, '', '', '', '']