effectivepython
effectivepython copied to clipboard
Item 11: The result of slicing a list is a whole new list...
In page 45,
The result of slicing a list is a whole new list. References to the objects from the original list are maintained. Modifying the result of slicing won't affect the original list:
I think this should be changed into:
References to the objects from the original list are not maintained.
https://stackoverflow.com/a/5131563/8621823
Based on above answer, I agree with the author that References to the objects from original list are maintained.
It could confusing because that statement in the book requires understanding in depth about how python works.
Also the statement Modifying
is vague on whether each item of original list is mutable or not, though i guess most readers will assume immutable items.
For mutable items, this sure does affect the original
l = [[1,2],[3,4],[5,6]]
l_slice = l[:2]
l_slice[1].append(5)
print(l_slice) #[[1, 2], [3, 4, 5]]
print(l) #[[1, 2], [3, 4, 5], [5, 6]]
Thank you for the report! I think it's clear as it is, but I could potentially explain more about references vs. objects to make it super clear.