user3813234 user3813234 - 1 year ago 124
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 Source

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())]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download