In python, what is the difference between slice with all the element and itself? [duplicate]

爱⌒轻易说出口 提交于 2020-01-30 11:04:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!