Python - Why does instruction "a[1:].remove(2)" do nothing? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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)

30th Sep 2019, 12:22 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
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.
30th Sep 2019, 12:34 PM
jtrh
jtrh - avatar
+ 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.
30th Sep 2019, 5:15 PM
Seb TheS
Seb TheS - avatar
+ 2
if you do a.remove(2) the result will be: [1, 2, 4]
30th Sep 2019, 3:21 PM
Lothar
Lothar - avatar