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...
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.
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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With