+ 1
Remove question
Need some better understanding: a=[2,1,2,4] a[1:].remove(2) Here is my interpretation: a[1] = 1, a[1:].remove(2) is to remove the first 2 from a[], but a[1:] does not include the first item in a, so nothing is removed. Is this kinda correct? It seems to me that anything inside [] would be ignored?
4 Respostas
+ 3
a[1:].remove(2) is doing nothing at all! see here my comments:
a=[2,1,2,4]
b = a[:] # or b = a[1:] this is how to make a copy from list a, it needs a name => b
a[1:].remove(2) # this does nothing, no copy of list (i checked it in debugger), not removing anything
#a.remove(2) # this does remove the first appearence of *2*
print(a[1:]) # this is a slice, that prints list a from index 1 up to the end so it's [1,2,4]
print(a) # this prints the complete list
+ 3
hi, here a description how to do it:
a=[2,1,2,4]
a.remove(2)
print(a)
In general: How remove(), del() and pop() are working:
*remove* removes the first matching value, not a specific index:
>>> a = [0, 2, 3, 2]
>>> a.remove(2)
>>> a
[0, 3, 2]
*del* removes the item at a specific index:
>>> a = [3, 2, 2, 1]
>>> del a[1]
>>> a
[3, 2, 1]
*pop* removes the item at a specific index and returns it.
>>> a = [4, 3, 5]
>>> a.pop(1)
3
>>> a
[4, 5]
+ 2
I think `a[1:]` creates a copy of <a> list, excluding the first item. And you invoke `remove` method on that copy, which doesn't affect the actual <a> list.
I think `a[1:].remove(2)` actually removes 2 from the copy [1,2,4] and ended as [1,4]. But since it's a copy, the changes made doesn't reflect on actual <a> list.
Or maybe I'm just lost here, or misunderstood your question altogether.
+ 1
When I execute:
a=[2,1,2,4]
a[1:].remove(2)
print(a[1:])
print(a)
This is the output:
[1, 2, 4]
[2, 1, 2, 4]
If a[1:] creates a copy of a, then how is a reference to the copy made?