DEV Community


Python: weird iterator behaviour after filtering out empty strings

harizio2 profile image Harizio2 ・1 min read

I was fiddling around with Python trying to learn some basics and while making a string replacer script I ran across a weird problem.
The following script was supposed to replace all instances of "Input" by each element in subs and print out all the replaced strings.

text = """
MyInput = GetSubsystem<Input>();
extern Input* MyInput;
Input* MyInput = 0;
texts = text.split("\n");
texts = filter(None,texts)#commenting this out fixes the iteration??
original = "Input";
subs = ["Time","WorkQueue","FileSystem","Log"]
sortbysubs = 1
separate = 0
print("number of subs:{} \n".format(len(subs)))
if (sortbysubs):
    for s in subs:
        for t in texts:
        if separate:print("")
    for t in texts:
        for s in subs:
        if separate:print("")

When sortbysubs = 0, it seems to work correctly: printing each line of text with each element in subs, and filtering out the empties beforehand.

When sortbysubs = 1, it only prints each text for the first element of subs.

Somehow there is a difference betweem printing "for s for t" rather than "for t for s".

Further more, this behaviour only emerges when filtering the texts for empties.
Commenting out the line "texts = filter(None,texts)" results in the problem disappearing.

Can anyone shed light on what exactly is happening here and how to fix it?


Editor guide
harizio2 profile image
Harizio2 Author

That makes sense!
Thanks for the help <3