Home > Enterprise >  ternary operator in list comprehension not working as expected
ternary operator in list comprehension not working as expected

Time:09-22

EDIT: this question turns out to be not related to list comprehension at all. The problem was caused by not passing the full path but only the filename into the os.path.isfile() which makes it always evaluate to False.

Why does the if/else at front of this list comprehension not work as expected? The statement below produced a list with all 0 (else case).

[1 if os.path.isfile(file) else 0 for file in os.listdir(path)]

The expected output will be 1 if the file is a file, and 0 if the file is a directory I have tested 1 if os.path.isfile(file) else 0 independently on another line and it works as expected (there are mixture of 1 and 0). I cannot find any syntax problem with my list comprehension statement.

What's more interesting is that if I replace the condition with something else, like 1 if file else 0, the behaviour flipped. Now every item become 1 even though some is expected to be 0 (Again, I verified them independently using the exact same conditional expression)

I have tried adding bool() to my condition but it does nothing. I also tried str(file) and also no difference.

CodePudding user response:

Try to pass the absolute path of the file to isfile function:

[1 if os.path.isfile(os.path.join(path, file)) else 0 for file in os.listdir(path)]

You can also achieve it without the if:

[int(os.path.isfile(os.path.join(path, file))) for file in os.listdir(path)]

CodePudding user response:

You can do it without ternary operator:

[int(os.path.isfile(os.path.join(path, file))) for file in os.listdir(path)]

or depending on what you plan to do with the resulting list:

[os.path.isfile(os.path.join(path, file)) for file in os.listdir(path)]

I would always prefer the later

  • Related