bslatkin / effectivepython

Effective Python: Second Edition — Source Code and Errata for the Book
https://effectivepython.com
2.2k stars 710 forks source link

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

Open ubless607 opened 2 years ago

ubless607 commented 2 years ago

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.

gitgithan commented 1 year ago

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]]
bslatkin commented 1 month ago

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.