简体   繁体   中英

Why doesn't copying and appending to a list in single line work in python

When i try to copy a part of list then append to it inline it doesn't work. For example:

a = [1, 2, 3, 4]
b = a[1:].append("x")

doesn't work but

b = a[1:]
b.append("x")

works. I couldn't understand why

list.append() is an in-place operation, meaning that it modifies the state of the list , instead of returning a new list object.

All functions in Python return None unless they explicitly return something else. The method a.append() modifies a itself, which means that there's nothing to return.

Another way you can see this behavior is in the difference between sorted(some_list) and some_list.sort() .

If you don't want to append "x" to a , then you'll need to use the second snippet, or you can simply concatenate:

>>> a = [1, 2, 3, 4]
>>> b = a[1:] + ["x"]
>>> b
[2, 3, 4, 'x']

To further clarify:

>>> a = [1, 2, 3, 4]
>>> b = a[1:].append("x")
>>> a
[1, 2, 3, 4]
>>> a[1:]
[2, 3, 4]
>>> type(b)
<class 'NoneType'>

Notice that b is None , since the list.append() method returns None . Notice also that a wasn't actually modified. This is because you were appending to a slice of a , but not actually saving that slice anywhere. Notice what happens if you do a.append("x") :

>>> b = a.append("x")
>>> a
[1, 2, 3, 4, 'x']
>>> type(b)
<class 'NoneType'>

b is still None , but now a got modified.

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