Search code examples
pythonpython-3.xlistmutability

why does variable assignment not work on lists sometimes


Python beginner here. Confused about the nature of list assignment.

a = [1, 2, 3]
b = a.reverse()
>>>a 
>>>[3,2,1]
>>>b
>>> # nothing shows up

or

e = [1,2,3]
f = e.append(4)
>>>e 
>>>[1,2,3,4]
>>>f
>>> # nothing shows up

Why does assigning to b or f not work here. I believe it has to do with the mutability of lists? Am i completely wrong? Thanks


Solution

  • Both these methods do an in-place modification, i.e.:

    b = a.reverse()
    f = e.append(4)
    

    They modify the original object and do not create a new one. Hence, you see None when you try and print these.

    As per @juanpa.arrivillaga:

    Note: The fact that these methods return None is a convention.