shubhamgoel27
shubhamgoel27

Reputation: 1439

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.

Upvotes: 4

Views: 690

Answers (3)

Mohammed Bahhari
Mohammed Bahhari

Reputation: 19

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

a.append(a[0])

and then exclude the first element

a[1:]

Upvotes: 0

Fogmoon
Fogmoon

Reputation: 569

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.

Upvotes: 1

Ofer Sadan
Ofer Sadan

Reputation: 11922

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]

Upvotes: 4

Related Questions