简体   繁体   中英

What's the difference between a=[1] and [1] in python?

When I do

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

the result is [1,2] - but the result of

print [1].append(2)

is None .

My understanding is that a is the reference of list object [1] . Everything in python is object. [1] is also a list object. a and [1] should be exactly the same. Why the result is totally different?

You have misunderstood your code. The difference has nothing to do with the variable; it is that in the second you are printing the return value from append , but append always returns None. If you printed a.append(2) in your first code you would also get None, except that a would have been modified in the meantime.

The None is the result of the method call on list.append . append modifies the list in place and does not return a new list. So you basically have appended 2 to [1] , but as you never stored the list you don't get to see the result.

The fact that append does not return a value (other than None ) is a hint already that the method is side-effecting (in this case mutating its argument).

If you want to return a new object each time you append to a list you should use + instead:

a = [1]
a + [2]
>>> [1, 2]

The value of a will not have changed now:

a
>>> [1]

You can chain this arbitrarily

a + [2] + [3,4] + [5]
>>> [1, 2, 3, 4, 5]

In

print [1].append(2)

you are printing the result of the list.append method, which is None .

In your first example, you are appending 2 to the list [1] and then print the list, the output is as expected.

In the second example you print the return value of [1].append(2) . What happens here is that you print the return value of append , which is None .

However, if you had a reference to your list, you could check that it is now modified. This little demo should make clear what happens:

>>> a = [1]
>>> print a.append(2) # This will print None
None
>>> a
[1, 2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM