Using a list method on an indexed list

Viewed 73

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?

1 Answers

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.

Related