26

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
  • 18,228
  • 35
  • 117
  • 186

7 Answers7

38
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
  • 194,053
  • 32
  • 286
  • 259
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
  • 79,172
  • 18
  • 156
  • 188
6

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
  • 129,524
  • 23
  • 177
  • 239
3
l = object.method()
l = l + [0 for _ in range(4 - len(l))]
glglgl
  • 85,390
  • 12
  • 140
  • 213
  • 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
  • 756,363
  • 169
  • 1,062
  • 1,111
2
self.my_list.extend([0 for _ in range(4 - len(self.my_list))])
Ned Batchelder
  • 345,440
  • 70
  • 544
  • 649
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
  • 172,072
  • 46
  • 300
  • 307