19/19 The Create Your Own Loop


This was supposed to print the "Smash" list without the characters in the "Notreal" list.

Smash = ['Mario', 'Link', 'Emira', 'Uru']

Notreal = ['Uru', 'Emira']

for char in Smash:
    for index in Notreal:
        if char == index:
    print Smash

What it actually does though, is print the Smash list, as such:

['Mario', 'Link', 'Uru']

Why's it doing this?


should it have printed:

['Mario', 'Link']

? it doesn't, because of index shift. the moment you remove Emira from the Smash list, Uru shifts to index 2 (where Emira used to be) and your for loop continues to the next index (3), which is now empty, so the loop exits.


So how do I resolve this issue? Run the another for Loop?


i would simply make and empty list and then do:

if index not in empty_list:

to append items not in the list to the list, removes becomes difficult, another loop might work, but if you lists becomes larger, this becomes a problem. Design of a problem is also importanat


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