It is quite inefficient to build the list bigger than you need it (particularly if n
gets large); instead, only add the padding you need. Also, it is Python convention to return None
if a function changes its argument(s) in-place:
def some_func(l, n, pad=0):
if len(l) >= n:
del l[n:]
else:
l.extend([pad] * (n - len(l)))
Example:
>>> l = [1, 2, 3, 4, 5]
>>> some_func(l, 3)
>>> l
[1, 2, 3]
>>> some_func(l, 5)
>>> l
[1, 2, 3, 0, 0]
Alternatively, return
a new list:
def some_func(l, n, pad=0):
if len(l) >= n:
return l[:n]
return l + ([pad] * (n - len(l)))