tags:

views:

292

answers:

3

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

+12  A: 

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.

Yossarian
+22 for user name
c0m4
+9  A: 

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?

Magnus Hoff
Um... right... I knew that...
c0m4
+3  A: 

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)
vartec
that seems less readable/understandable than using copy...Is there a reason it's "often used"?
tgray
I agree it's less readable. Why it's used? I guess, that's because it doesn't require import.
vartec
Do you think they're avoiding the import because it takes another line of code, or because they're trying to avoid some sort of overhead (memory, load-time, etc.)?
tgray
well, for example list1[:] is an expression. copy.copy(list1) also is expression. But import copy; copy.copy(list1) isn't.
vartec
BTW. it's recognized in the documentation. http://docs.python.org/library/copy.html "Shallow copies of dictionaries can be made using dict.copy(), and of lists by assigning a slice of the entire list, for example, copied_list = original_list[:]"
vartec