0

I want to zero pad a list to a certain length in python, so I can do this:

>>> a = [1,2,3,4]
>>> b = [0,1]
>>> rng = max(len(l) for l in [a,b])
>>> for lst in [a, b]:
...    apnd = [0]*(rng-len(lst))
...    lst += apnd
... 
>>> a
[1, 2, 3, 4]
>>> b
[0, 1, 0, 0]

But lets say I want to prepend that list instead:

>>> a
[1, 2, 3, 4]
>>> b
[0, 1, 0, 0]
>>> a = [1,2,3,4]
>>> b = [0,1]
>>> rng = max(len(l) for l in [a,b])
>>> for lst in [a, b]:
...    prpnd = [0]*(rng-len(lst))
...    lst = prpnd + lst
... 
>>> a
[1, 2, 3, 4]
>>> b
[0, 1]

This doesn't work. Why does the '+=' operator work inside a for loop, but the '=' operator doesn't?

What is a way that I can prepend onto a list inside this for loop?

kingledion
  • 2,263
  • 3
  • 25
  • 39
  • 2
    Because `__iadd__` is different to `__add__`; the former mutates the current list, the latter creates a new list. See e.g. https://stackoverflow.com/q/2347265/3001761. A one-line prepend would be e.g. `lst[:0] = prpnd`. – jonrsharpe Feb 03 '18 at 16:07
  • 1
    The assignment operator `=` will not change existing objects. It only binds a name (on the left) to an object (on the right). The names `a` and `lst` just end up pointing to different objects instead of the same object – Patrick Haugh Feb 03 '18 at 16:09
  • @vaultah the linked question does not mention how to prepend to a list... – Norrius Feb 03 '18 at 16:21
  • 1
    @Norrius fair enough, added another dupe target. Martijn's answer modifies the list in place – vaultah Feb 03 '18 at 16:25

0 Answers0