Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padding a list in python with particular value [duplicate]

Tags:

python

list

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)
like image 721
MxLDevs Avatar asked Aug 11 '11 12:08

MxLDevs


People also ask

How do I add a zero padding in Python?

Python String zfill() MethodThe zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length. If the value of the len parameter is less than the length of the string, no filling is done.

How do you extend the length of a list in Python?

The list extend() method in Python is used to add the elements of the iterable at the end of the current list as list elements. The length of the iterable increases the length of the original list. On the other hand, the list append() method is used to add the object at the end of the current list as a single element.

How do you make a list of zeros in Python?

The easiest and most used method for creating a list with only zeros is the use of the steric “*” operator in the python code.


4 Answers

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]
like image 192
eumiro Avatar answered Oct 19 '22 15:10

eumiro


>>> 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)
like image 39
Shawn Chin Avatar answered Oct 19 '22 14:10

Shawn Chin


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]
>>> 
like image 6
Johnsyweb Avatar answered Oct 19 '22 16:10

Johnsyweb


Another way, using itertools:

from itertools import repeat
self.my_list.extend(repeat(0, 4 - len(self.my_list)))
like image 3
Felix Kling Avatar answered Oct 19 '22 14:10

Felix Kling