jevans
jevans

Reputation: 399

Combining for and if loops

I have the code:

num_for_loops = 0
for line in lines:
    if line.strip().startswith('for '):
        num_for_loops += 1
return num_for_loops

I need to condense it down to as little lines as possible. Is there a way to do this by combining the for and if statements? The context is irrelevant.

Upvotes: 2

Views: 409

Answers (2)

Kirk Strauser
Kirk Strauser

Reputation: 30957

Generator expressions always win concise code contests:

return sum(1 for line in lines if line.strip().startswith('for '))

That generates a series of 1s equal in length to the number of lines starting with 'for ', summing the list as it's generated so that you could parse terabytes of data without running out of memory.

Upvotes: 3

Nolen Royalty
Nolen Royalty

Reputation: 18663

num_for_loops = sum(line.strip().startswith("for ") for line in lines)

since you're immediately returning num_for_loops I suppose you really just want

return sum(line.strip().startswith("for ") for line in lines)

Upvotes: 9

Related Questions