I am fairly new to Python, and was recently surprised by the following behavior:
If I have a list and remove an element by value:
lst=[1,2,3,4,5,6]
lst.remove(3)
print(lst)
I get the expected result
[1,2,4,5,6]
If I type an indexed list, I get the expected result:
type(lst[2:])
list
But if I apply a list method to an indexed list, I do not get list modified in place as I expect.
lst=[1,2,3,4,5,6]
#type(lst[2:])
lst[2:].remove(3)
print(lst)
[1,2,3,4,5,6]
Is this because the indexed list is not actually the same list as the original list (from the perspective of the .remove() method?
1st[2:] is called slicing. It creates a copy of your list starting from the 2nd index to the last.
So when you use the remove function it removes the element from the copy rather than the original.
Use:
lst = lst[2:]
lst.remove(3)
This will give you the answer you expect to see.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With