0

I noticed something odd demonstrated below:

>>> print [].append(1)
None

>>> a = [].append(1)
>>> print a
None

>>> a = []
>>> a.append(1)
>>> print a
[1]

I do not understand what the difference between the first two statements and the last one is. Can anyone explain?

EDIT:

This question was asked poorly. I should also have noted that:

>>> print [] + [1]
[1]

Thank you for explaining that the return value for operations on mutable data-types in python is normally None.

kingledion
  • 2,263
  • 3
  • 25
  • 39
  • How does last example remotely resemble the first two? – user2390182 May 06 '16 at 13:29
  • `List.append` dosen't return anything so first two statements will be `None` but third one is a list with appended element – ᴀʀᴍᴀɴ May 06 '16 at 13:29
  • 3
    `list.append` mutates its list and returns `None`. This is a standard convention in Python for functions and methods that perform mutation on an object, like the `list.` methods. In contrast, Python strings are immutable, so `str.` methods cannot mutate their target object, they must return a new object. – PM 2Ring May 06 '16 at 13:34
  • Thank you PM 2Ring, mutable vs immutable was my real question, it seems. – kingledion May 06 '16 at 13:36

1 Answers1

2

The .append() method does not return a modified list as you would expect.
With this line a = [].append(1) you're assigning the return value (which is None in Python by default) to the variable a. You're not assigning an array that you've just appended to.
However, with this code

>>> a = []
>>> a.append(1)

you're modifying the array in the variable a.

illright
  • 3,991
  • 2
  • 29
  • 54