问题
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 attempted following line and it gives me the same result.
numbers = [n for n in numbers if n % 2 == 0]
I understand that [:]
means that its array with all the elements.
What is the purpose of attempting to assign to array with full element?
回答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]
来源:https://stackoverflow.com/questions/59849248/in-python-what-is-the-difference-between-slice-with-all-the-element-and-itself