user3813234 user3813234 - 8 months ago 57
Python Question

python: add str and str.title() to list using list comprehension

I am reading in a file with words, like this:

stop_words = [x for x in open('stopwords.txt', 'r').read().split('\n')]

but I also need the title() version of the word in the same list. Can I do this using one list comprehension?


In one (nested) list comprehension:

stop_words = [y for x in open('stopwords.txt', 'r').read().split('\n') for y in (x, x.title())]

Edit: You actually shouldn't do it like this, because you lose the file object to the open file and can't close it. You should use a Context Manager:

with open('stopwords.txt', 'r') as f:
    stop_words = [y for x in'\n') for y in (x, x.title())]