My for loop is ignoring an item in a list


#1



19. Create Your Own


I have no error message; this is a semantic error. My code is ignoring the string, "computers" in a list over which I am using a for loop nested in another for loop.


The purpose of the first for loop is to iterate over every string in genericList. At every string, I want the second for loop to iterate over every character within the string and remove the string from genericList if it finds an "r".


genericList = ["pie","harpoons","Halloween Candy","razors","computers","toys","viruses"]
for stuff in genericList:
    for char in stuff:
        if char == "r":
            genericList.remove(stuff)
            break
else:
    print "Here you go!"
    print genericList


#2

Hi @aspirant14,

Changing the length of a list as you are iterating over that list interferes with the iteration process by changing the positions of items in the list. This line changes the length of genericList ...

genericList.remove(stuff)

What you should do here is create a new empty list. As you iterate through the original list, append items to the new list that do not contain "r".

EDITED to add this suggestion ...
If your revised code still contains nested for loops, you could associate else blocks with both the inner and the outer loop. Another approach would be to replace the inner loop with a test that uses the in operator to determine whether an item in the list contains "r".


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.