In Python, What Is The Difference Between Slice With All The Element And Itself?
I saw a following line and I have difficulty understanding why someone would express it this way. numbers = list(range(10)) numbers[:] = [n for n in numbers if n % 2 == 0] I attem
Solution 1:
numbers[:] = something
is known as slice assignment. It replaces the elements in the selected slice (the whole array in this case), with the elements to the right of the assignment.
numbers = something
is regular assignment, which makes numbers point to something
.
This example illustrates the differences:
numbers = [1, 2, 3]
something = [4, 5, 6]
numbers = something
something[0] = 10
print(numbers) # [10, 5, 6]
Notice how we may have wanted to modify the something
list, but we unexpectedly modified numbers
! Because they point to the same list. However, things are different with slice assignment:
numbers = [1, 2, 3]
something = [4, 5, 6]
numbers[:] = something
something[0] = 10
print(numbers) # [4, 5, 6]
numbers
is still the same.
As pointed by user Tomerikoo in the comments, the slice's size doesn't have to match with whatever it's being replaced with. Which means the following is valid:
numbers = [1, 2, 3]
numbers[:] = [4, 5, 6, 7, 8, 9]
Post a Comment for "In Python, What Is The Difference Between Slice With All The Element And Itself?"