Search code examples
pythonif-statementin-operator

python if (X not in Y) or (Z not in Y) condition unexpected result


There is a list of file names, like:

files = ["f1", "f2", "f3", "f4", "f1.txt", "f3.pdf"]

and I want to find those files that have a "txt" or "pdf" equivalent with the same name and remove them from the list. so the desired output is f2 f4 f1.txt f3.pdf
I tried this:

for f in files: 
     if f+".txt" not in files or f+".pdf" not in files: 
         print(f)

output: f1 f2 f3 f4 f1.txt f3.pdf which is wrong.

I also tried with parenthesizes around each condition and not f+".txt" in files but no luck.
By removing both or one of "not"s, the output is as expected:

for f in files: 
     if f+".txt" in files or f+".pdf" in files: 
         print(f)

output: f1 f3
To get the desired output, I can use a pass statement in if block and print(f) in an else block.
But the question is "why does not the first code work?" I searched a little bit before posting but they weren't exactly what I was looking for.


Solution

  • Try this code :

    files = ["f1", "f2", "f3", "f4", "f1.txt", "f3.pdf"]
    for f in files: 
         if f+".txt" not in files and f+".pdf" not in files:
             print(f)