Guided Project: Winning Jeopardy weird behaviour

Screen Link:

My Code:

# Top half code:
row = jeopardy.loc[2]
split_question = row['clean_question'].split(' ')

for word in split_question:
    print(word, len(word), len(word) < 6)
    if len(word) < 6:
        split_question.remove(word)
print(split_question)

# Bottom half code

row = jeopardy.loc[2]
split_question = row['clean_question'].split(' ')

for word in split_question:
    print(word, len(word), len(word) < 6)
#     if len(word) < 6:
#         split_question.remove(word)
print(split_question)
Replace this line with your code

What I expected to happen:

Removal of ‘26’ and ‘this’ from the list, since their length is shorter than the requirement.

What actually happened:

During this part of the Guided Project for Jeopardy, you’re tasked with removing words whose length is lower than 6. But as you can see, some words shorter than that still remain. The program seems to ignore a couple of words for no reason.

On the top half, you can see the loop ignores ‘26’ and ‘this’ and prints them even though they’re indeed shorter than 6 characters.

On the bottom half, you can see that if I don’t do the removal process, then the loop actually sees ‘26’ and ‘this’.

This is a side-effect of trying to remove an item from a list as you are iterating through it. That’s usually not recommended at all, because it can lead to the kind of behavior you are observing now.

So, modify your approach so that you are not removing items from split_question as you iterate through it. Couple of ways you could do that -

  • Create a copy of that list, and remove items from that copy while you loop through split_question
  • Create an empty list, and instead of removing items, add items to that new empty list which are greater in length than 6.

Of course! No wonder the elements that go-remain alternate between each other.

index 0 = ‘washington’ -> stays
index 1 = ‘proclaimed’ -> stays
index 2 = ‘nov’ -> goes, now index 2 is occupied by ‘26’.
index 3 = used to be ‘26’, now is ‘1789’ -> goes, now index 3 is occupied by ‘this’
index 4 = used to be ‘this’, now is ‘first’ -> goes

Thanks for the explanation!

1 Like

In addition to @the_doctor response, it is not advisable to iterate (using for loop) over the same list when using remove method. You may refer to this link https://stackoverflow.com/questions/10665591/how-to-remove-list-elements-in-a-for-loop-in-python for further explanation.