Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One line for loop to add elements to a list in Python

I am trying to remove stop words (from nltk) from my data set but not sure why the one line query is not working:

filtered_words = [word if word not in stop_words for word in words]

This is what I need to do:

filtered_words = []
for word in words:
    if word not in stop_words:
        filtered_words.append(word)
like image 638
Aditya Landge Avatar asked Oct 28 '25 16:10

Aditya Landge


2 Answers

the if has to be at the end of the list comprehension:

filtered_words = [word for word in words if word not in stop_words]

see: https://www.pythonforbeginners.com/basics/list-comprehensions-in-python

like image 99
AlessioM Avatar answered Oct 31 '25 07:10

AlessioM


syntax you want is :

x = [x for x in range(200) if x%3 == 0 ]

put condition behind for

the syntax you have requires else like :

x = [x if x%3 == 0  else None for x in range(200)  ]

and this produces an error:

x = [x if x%3 == 0  for x in range(200)  ]
like image 33
user8426627 Avatar answered Oct 31 '25 07:10

user8426627



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!