Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

slice

Lest 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...

like image 893
c0m4 Avatar asked Mar 25 '09 11:03

c0m4


3 Answers

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

like image 57
nothrow Avatar answered Oct 13 '22 12:10

nothrow


list[-1:] creates a new list. To get the same behaviour as list[len(list)-1] it would have to return a view of some kind of list, but as I said, it creates a new temporary list. You then proceed to edit the temporary list.

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

like image 24
Magnus Hoff Avatar answered Oct 13 '22 12:10

Magnus Hoff


Slicing creates copy (shallow copy). It's often used as an shallow copy idiom.

i.e.

list2 = list1[:]

is equivalent to

import copy
list2 = copy.copy(list1)
like image 37
vartec Avatar answered Oct 13 '22 12:10

vartec