N=8
f,g=4,7
indexList = range(N)
print indexList
print f, g
indexList.pop(f)
indexList.pop(g)
In this code I am getting an error stating that the pop index of g
in indexList
is out of range.
Here is the output:
[0, 1, 2, 3, 4, 5, 6, 7]
4 7
Traceback (most recent call last):
indexList.pop(g)
IndexError: pop index out of range
I don't understand, g
has a value of 7, the list contains 7 values, why is it not able to return me the 7 in the list?
To get the final value of a list pop'ed, you can do it this way:
>>> l=range(8)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7]
>>> l.pop(4) # item at index 4
4
>>> l
[0, 1, 2, 3, 5, 6, 7]
>>> l.pop(-1) # item at end - equivalent to pop()
7
>>> l
[0, 1, 2, 3, 5, 6]
>>> l.pop(-2) # one left of the end
5
>>> l
[0, 1, 2, 3, 6]
>>> l.pop() # always the end item
6
>>> l
[0, 1, 2, 3]
Keep in mind that pop removes the item, and the list changes length after the pop. Use negative numbers to index from the end of a list that may be changing in size, or just use pop() with no arguments for the end item.
Since a pop can produce these errors, you often see them in an exception block:
>>> l=[]
>>> try:
... i=l.pop(5)
... except IndexError:
... print "sorry -- can't pop that"
...
sorry -- can't pop that
After you pop the 4, the list only has 7 values. If you print indexList
after your pop(f)
, it will look like:
[0, 1, 2, 3, 5, 6, 7]
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