user3813234 user3813234 - 27 days ago 20
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?

Answer

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 f.read().split('\n') for y in (x, x.title())]