0
Python - Why does instruction "a[1:].remove(2)" do nothing?
a = [2,1,2,4] print(a[1:]) a[1:].remove(2) print(a)
3 Answers
+ 4
a[1:] is called list slicing, this sliced list is actually a shallow copy and therefore calling it's remove method will not alter the original list.
+ 3
in the given code clip, a and a[1:] are 2 independent objects, changes on a and a[1:] won't affect each other.
This is how it could be fixed:
a = [2, 1, 2, 4]
b = a[1:]
b.remove(2)
a[1:] = b
del b
print(a)
It might be confusing because I just told that a and a[1:] are 2 different objects, but it works little different when assigning valued to the slice.
+ 2
if you do a.remove(2) the result will be:
[1, 2, 4]