30

Possible Duplicate:
Some built-in to pad a list in python

I have a method that will return a list (instance variable) with 4 elements. Another method is used to assign values to the list.

But at the moment I can't guarantee that the list has 4 elements when it's asked for, so I want to fill it up with 0's.

Is there a way to fill it with 0's other than say a loop?

for i in range(4 - len(self.myList)):
   self.myList.append(0)
Community
  • 1
  • 1
MxLDevs
  • 19,048
  • 36
  • 123
  • 194

7 Answers7

39
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]
eumiro
  • 207,213
  • 34
  • 299
  • 261
10
>>> 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)
Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
7

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]
>>> 
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
3
l = object.method()
l = l + [0 for _ in range(4 - len(l))]
glglgl
  • 89,107
  • 13
  • 149
  • 217
  • Right. Originally I wanted to add something like `list = (list + [0 for _ in range(4)])[:4]` and then realized that it works simpler. – glglgl Aug 11 '11 at 13:49
  • 2
    You really shouldn't use `list` for your var name. That will overwrite the builtin `list()`. – Shawn Chin Aug 11 '11 at 14:52
  • For me, except for the variable name as @ShawnChin said, it is the best one-line (I already have my list in a variable and post process it afterward to complete it), easily understandable. Thanks then. – gluttony Jan 13 '21 at 10:24
  • You both are right, I changed my variable name now. – glglgl Jan 14 '21 at 06:46
3

Another way, using itertools:

from itertools import repeat
self.my_list.extend(repeat(0, 4 - len(self.my_list)))
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
2
self.my_list.extend([0 for _ in range(4 - len(self.my_list))])
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
2

A hacky append-and-cut solution:

>>> x = [1,2]
>>> (x + [0] * 4)[:4]
[1, 2, 0, 0]

Or:

>>> (x + [0] * (4 - len(x)))
[1, 2, 0, 0]
miku
  • 181,842
  • 47
  • 306
  • 310