Adam_G
Adam_G

Reputation: 7879

Python Nested Loop Comprehension

I am trying to set a "word_count" variable by looping through sentences in a file. The file looks like:

I am Sam
I am Alex
Alex likes Sam

I can do:

word_count = 0
for line in file:
    word_count += enumerate(line.split())

How do I make this one line?

Upvotes: 0

Views: 41

Answers (2)

Anshul Goyal
Anshul Goyal

Reputation: 76887

You could use builtin sum to do this

word_count = sum(len(line.split()) for line in file)

Upvotes: 4

avinash pandey
avinash pandey

Reputation: 1381

You can use sum along with the len function to achieve this in one line

word_count = sum(len(line.split()) for line in file)

Upvotes: 2

Related Questions