简体   繁体   中英

Python List Append not working on sliced lists

I have a list a = [1,2,3,4,5]

I don't understand why the following code doesn't produce [2,3,4,5,1]

a[1:].append(a[0])

I tried reading up on the append() method as well as list slicing in Python, but found no satisfactory response.

a[1:] gives you a whole new list , but you're not assigning it to any variable so it it just thrown away after that line. You should assign it to something (say, b ) and then append to it (otherwise append would change the list but return nothing):

a = [1,2,3,4,5]
b = a[1:]
b.append(a[0])

And now b is your desired output [2,3,4,5,1]

I think here you just not really understand append function. Just like my answer in Passing a variable from one file into another as a class variable after inline modification , append is an in-place operation which just update the original list and return None.

Your chain call a[1:].append(a[0]) will return the last call return value in the chain, so return append function value, which is None.

Just like @flakes comment in another answer, a[1:] + a[:1] will return your target value. Also you can try a[1:][1:][1:] which will return some result. So the key point is the append function is in-place function.

See python more on list

You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None . 1 This is a design principle for all mutable data structures in Python.

First, append the first element a[0] to the list

a.append(a[0])

and then exclude the first element

a[1:]

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