Padding a list in python with particular value

Why not create a little utility function?

>>> def pad(l, content, width):
...     l.extend([content] * (width - len(l)))
...     return l
... 
>>> pad([1, 2], 0, 4)
[1, 2, 0, 0]
>>> pad([1, 2], 2, 4)
[1, 2, 2, 2]
>>> pad([1, 2], 0, 40)
[1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> 

self.myList.extend([0] * (4 - len(self.myList)))

This works when padding with integers. Don't do it with mutable objects.

Another possibility would be:

self.myList = (self.myList + [0] * 4)[:4]

>>> out = [0,0,0,0]   # the "template" 
>>> x = [1,2]
>>> out[:len(x)] = x 
>>> print out
[1, 2, 0, 0]

Assigning x to a slice of out is equivalent to:

out.__setitem__(slice(0, len(x)), x)

or:

operator.setitem(out, slice(0, len(x)), x)

Another way, using itertools:

from itertools import repeat
self.my_list.extend(repeat(0, 4 - len(self.my_list)))

Tags:

Python

List