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)
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.
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.
The easiest and most used method for creating a list with only zeros is the use of the steric “*” operator in the python code.
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)
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]
>>>
Another way, using itertools
:
from itertools import repeat
self.my_list.extend(repeat(0, 4 - len(self.my_list)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With