Reputation: 7879
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
Reputation: 76887
You could use builtin sum
to do this
word_count = sum(len(line.split()) for line in file)
Upvotes: 4
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