Python Pop Quiz - List Popping
The Python list data type is much like an array in other programming languages. The list includes many different methods. You can get a full listing of those methods like this:
my_list = []
print(dir(my_list))One of those methods is called pop(). You can pass an index of the item you want to pop from the list (if you don’t, the last item is chosen). That means you are removing an item from the list.
But what happens if you iterate over the list and attempt to remove some items? If you know the answer to that, this quiz will be easy!
The Quiz
What does the my_list look like after this code runs?
my_list = list(range(1, 7))
for index, item in enumerate(my_list): my_list.pop(index)
print(my_list)A) []
B) [1, 3, 5]
C) [2, 4, 6]
D) An IndexError is raised
Hint
What does enumerate() do?
The Answer
C) [2, 4, 6]
Explanation
This code runs because you never hit an index that no longer exists in the list.
You can rewrite this code without the enumerate() function at all and it will still work:
>>> my_list = list(range(1, 7))
>>> index = 0
>>> for item in my_list:
... my_list.pop(index)
... index += 1
...
>>> print(my_list)
[2, 4, 6]However, there is a way to get an IndexError if you’re not careful. Try writing the code like this:
>>> my_list = list(range(1, 7))
>>> for item in my_list:
... my_list.pop(item)
...
Traceback (most recent call last):
Python Shell, prompt 2, line 2
builtins.IndexError: pop index out of rangeThis code raises an IndexError, but why? The problem here is that pop() takes an index, but you are passing in the item itself, which is an integer. If you put in an integer that is greater than the current length of the list, you will get an IndexError!
If you made a list of only zeros, it would work fine:
>>> my_list = [0, 0, 0, 0, 0, 0, 0]
>>> for item in my_list:
... my_list.pop(item)
...
>>> my_list
[0, 0, 0]The lesson here is that you should never modify an iterable that you are actively iterating over, or you can end up with common or weird logic errors.


