effectivepython icon indicating copy to clipboard operation
effectivepython copied to clipboard

Item 11: The result of slicing a list is a whole new list...

Open ubless607 opened this issue 3 years ago • 2 comments

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.

ubless607 avatar Jul 11 '21 18:07 ubless607

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

gitgithan avatar Jun 11 '23 15:06 gitgithan

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.

bslatkin avatar May 31 '24 23:05 bslatkin