My goal is to take a list of unknown number of elements and extend/slice it to exactly n
elements, padding lists that are too short with 0
and slicing lists that are too long.
For example
n = 10
foo = [1,2,3,4]
print some_func(foo,n)
should return [1,2,3,4,0,0,0,0,0,0]
, and
n = 10
foo = [1,2,3,4,5,6,7,8,9,10,11,12]
print some_func(foo,n)
should return [1,2,3,4,5,6,7,8,9,10]
Right now I'm doing this:
def some_function(l, n):
l.extend([0] * n)
l = l[:n]
return l
But that seems inefficient. Is there a more pythonic way of doing this?
EDIT: point of clarification, I am not trying to modify the original array, I am returning a new array that can be a shallow copy.