So the following is confusing me.
#!/usr/bin/python
test = [0, 0, 0, 1, 2, 3, 4, 5, 6]
test1 = [0, 0, 0, 1, 2, 3, 4, 5, 6]
for _dummy in test:
if(_dummy == 0):
test.pop()
for _dummy in test1:
if(_dummy == 0):
test1.pop(0)
print test
print test1
Results
ubuntu-vm:~/sandbox$ ./test.py
[0, 0, 0, 1, 2, 3]
[0, 1, 2, 3, 4, 5, 6]
Perhaps, I'm fundamentally misunderstanding how pop is implemented. But my understanding is that it removes the item at the given index in the list, and returns it. If no index is specified, it defaults to the last item. So it would seem that in the first loop it should remove 3 items from the left of the list, and in the second loop it should remove 3 items from the end of the list.
When you use the ' for item in ITEMS: ' command in python; you're still iterating by index, item is still implicitly set as item = ITEMS[index] . each pop(0) shifts the items to the left, and the next item is referenced as item = ITEMS[index++] , so, the third zero in test1 is never processed by the loop.
Python List pop() First / Front / Left / Head. The list. pop(index) method to with the optional index argument to remove and return the element at position index from the list. So if you want to remove the first element from the list, simply set index=0 by calling list. pop(0) .
The pop() method removes the element at the specified position.
The time complexity of the python list pop() function is constant O(1). It does not matter how many elements are in the list, removing an element from a list takes the same time and it does not depend on the number of elements to be popped. The reason for this is that in cPython lists are implemented with arrays.
The first test isn't surprising; three elements are removed off the end.
The second test is a bit surprising. Only two elements are removed. Why?
List iteration in Python essentially consists of an incrementing index into the list. When you delete an element you shift all the elements on the right over. This may cause the index to point to a different element.
Illustratively:
start of loop
[0,0,0,1,2,3,4,5,6]
^ <-- position of index
delete first element (since current element = 0)
[0,0,1,2,3,4,5,6]
^
next iteration
[0,0,1,2,3,4,5,6]
^
delete first element (since current element = 0)
[0,1,2,3,4,5,6]
^
and from now on no zeros are encountered, so no more elements are deleted.
To avoid confusion in the future, try not to modify lists while you're iterating over them. While Python won't complain (unlike dictionaries, which cannot be modified during iteration), it will result in weird and usually counterintuitive situations like this one.
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