Friday, April 5, 2019

python - How is `var[:] = []` different from `var = []`?





I normally understand how slices behave to the left and right of the assignment operator.



However, I've seen this in the Python (3.8.0) manual and trying to figure out what I'm missing.






letters[:] = []





How's that different from just letters = []?



(It's not easy to search for [:] as stackoverflow thinks you're looking for a tag. So, if there is already an answer I couldn't locate it.)



I see some rather irrelevant answers. So, to hopefully clarity, the question is not about what the [:] slice means, rather about assigning the empty list to one.


Answer



This code demonstrates what is going on:



original = ['a','b','c']


letters = original

print('Same List')
print(original)
print(letters)

letters = []

print('Different lists')
print(original)

print(letters)

letters = original

letters[:] = []

print('Same list, but empty')
print(original)
print(letters)



Output:



Same List
['a', 'b', 'c']
['a', 'b', 'c']
Different lists
['a', 'b', 'c']
[]
Same list, but empty

[]
[]


The first part of the code: letters = original means that both variables refer to the same list.



The second part: letters = [] shows that the two variables now refer to different lists.



The third part: letters = original; letters[:] = [] starts with both variables referring to the same list again, but then the list itself is modified (using [:]) and both variables still refer to the same, but now modified list.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...