19/19 The Create Your Own Loop


#1

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:
            Smash.remove(index)
else:
    print Smash

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

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

Why's it doing this?


#2

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.


#3

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


#4

i would simply make and empty list and then do:

if index not in empty_list:
   empty_list.append(index)

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


#5

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