Python - Sum not working in list comprehension syntax if the source is file

list-comprehension, python, sum

Solution

The simplest solution is this:

with open("words.txt") as words:
  sum(1 for word in words if "e" not in word)

As you can see, `sum` does work with any iterator - here I am using a generator expression.

Rather than doing `word.find('e') == -1` we can just do `"e" not in word` which is nicer to read and works as strings are iterable themselves and support `__contains__`.

I am also using the `with` statement to open files - this is preferable to manually opening and closing them as it handles those things for you, and handles exceptions correctly too.

I would like to note however, your example works for me. My guess is that your file is space or comma delimited, but looping through a file returns lines.

My test file:

bob
bill
james
test
something
no

This, for example, will not work:

bob bill james test something no

As we will get one string containing the whole thing. In this case, we can use `str.split()` to split the lines into words.

E.g:

with open("words.txt") as lines:
    sum(1 for line in lines for word in line.split() if "e" not in word)

Problem

I'm a newbie in Python and I'm studying list comprehension. What I'm trying to do is to convert the following code into list comprehension: ``` def words_without_e(): count = 0 words = open('words.txt') for word in words: if word.find('e') == -1: count += 1 words.close() return count ``` Here's my feeble attempt: ``` words = open('words.txt') print sum([1 for word in words if word.find('e') == -1]) ``` But unfortunately it's not working. The answer I expect to get is 37641, but I'm getting 0. :( I tried creating another code doing the same thing but instead of file as source, I used a list: ``` def test(): words = ['hello', 'world', 'ciao'] return sum([1 for word in words if word.find('e') == -1]) ``` And it works. I saw this "quite" similar SO post and tried the code posted there `return len([word for word in words if len(word) >= 2 and word[0] == word[-1]])`. It works if the source is a hard-coded list but fails if the source is an external file. Now, my question is, does `sum` only works with lists and tuples? If I understood the docs correctly, any iterable could be summed up. Any enlightenment would be very much appreciated. :)

Original source

Related problems