Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 589
user3813234 Avatar asked Sep 01 '26 23:09

user3813234


1 Answers

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())]
like image 190
Patrick Haugh Avatar answered Sep 04 '26 13:09

Patrick Haugh