F.Lira
F.Lira

Reputation: 653

Compile an 'if' in a "for" at the same line

Just for curiosity and knowledge, of course. Do you have any suggestion to compile these two lines in a single line?

What I have now:

for files in os.listdir(path):
    if files.endswith("geneclusters.txt"):

What I am trying to obtain:

for (files in os.listdir(path)) if files.endswith("geneclusters.txt"):

Any suggestion?

Upvotes: 0

Views: 65

Answers (3)

MisterMiyagi
MisterMiyagi

Reputation: 50116

You cannot merge an if statement into a for statement. However, you can use a generator expression inside a for statement.

#            V --- generator expression ---------------------------------------------- V
for files in (files for files in os.listdir(path) if files.endswith("geneclusters.txt")):
    ...

Note that there is no performance advantage, and in fact this is usually slower. On top, it is generally less readable.

Do not use a list comprehension, delimited by [] instead of (), for such use cases. It creates the entire intermediate list in memory.

Upvotes: 1

Nordle
Nordle

Reputation: 2981

Of course (using list comprehension), depending on what you want to do next:

for file in [f for f in os.listdir(path) if f.endswith("geneclusters.txt")]:

Upvotes: 0

blhsing
blhsing

Reputation: 106618

You can use list comprehension:

for files in [f for f in os.listdir(path) if f.endswith("geneclusters.txt")]:

Upvotes: 1

Related Questions