What is the difference between list [-1:] [0] and list [len (list) -1]?

Lets say you want the last element of a python list: what is the difference between

myList[-1:][0] 

and

 myList[len(myList)-1] 

I thought there was no difference, but then I tried this

 >>> list = [0] >>> list[-1:][0] 0 >>> list[-1:][0] += 1 >>> list [0] >>> list[len(list)-1] += 1 >>> list [1] 

I was a little surprised ...

+7
python list slice
source share
3 answers

if you use slicing [-1:], the returned list is a shallow copy, not a link. therefore, [-1:] [0] modifies the new list. [len (list) -1] refers to the last object.

+14
source share

list[-1:] creates a new list. To get the same behavior as list[len(list)-1] , it would have to return an idea of ​​some list , but, as I said, it creates a new temporary list. Then go on to edit the temporary list.

Anyway, you know that you can use list[-1] for the same thing, right?

+9
source share

Slicing creates a copy (shallow copy). It is often used as a shallow copy.

i.e.

 list2 = list1[:] 

equivalently

 import copy list2 = copy.copy(list1) 
+3
source share

All Articles