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:
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:
Along with all the other answers, the important part about the
pop()
function is that it removes the value from the array, thus changing the indexes. After popping index 4, your list is left with 7 items. It is important to know that Python indexes starting at 0 so your 7 item list only contains indexes 0 through 6. That's why popping index 7 is out of bounds, it no longer exists.Typically a "popping" function is used when implementing a stack or a queue where the goal is to get a value from a list of values waiting to be processed. To avoid processing the same data twice by accident, you make sure to remove it at the same time as retrieval.
Sometimes stacks and queues can be implemented with a
peek
operation that will return just the value without removing it but since Python implements stacks and queues just using regular arrays without any special wrapper, your peek function would be the standardarray[index]
call.----EDIT----
It occurs to me that it could be the case that instead of removing the item at index 7, you wish to remove the value 7. If that's the case, you should call
indexList.remove(7)
. This will remove the first instance of7
in your list, no matter what its index (and throws an error if there is no value7
). I'm pretty sure you understand thatpop()
takes an index, though.Just in case, take a look at the Python datastructures API for more information on what functions are available, what they do, and what arguments they take.
After you pop the 4, the list only has 7 values. If you
print indexList
after yourpop(f)
, it will look like: