Py_Student
Py_Student

Reputation: 159

Appending list inside a for loop

I have a two item list, each item is a string of text. I want to loop around both items and basically remove a word if it is NOT in a set of words. However the following code is putting all the words together, instead of created two separate items. I want my updated_list to have two items, one for each original item im updating:

#stopwords is a variable for a set of words that I dont want in my final updated list
updated_list = []
articles = list_of_articles

for article in articles:
    for word in article:
         if word not in stopwords:
              updated_list.append(word)


articles = [['this, 'is', 'a', 'test'], ['what', 'is', 'your', 'name']]
stopwords = {'is', 'a'}

expected output:
updated_list = [['this, 'test'],['what', 'your', 'name']]

current output:
updated_list = ['this, 'test','what', 'your', 'name']

Upvotes: 1

Views: 1505

Answers (4)

Andrej Kesely
Andrej Kesely

Reputation: 195408

If you prefer list comprehensions, you can use this example:

articles = [['this', 'is', 'a', 'test'], ['what', 'is', 'your', 'name']]
stopwords = {'is', 'a'}


articles = [[word for word in article if word not in stopwords] for article in articles]
print(articles)

Prints:

[['this', 'test'], ['what', 'your', 'name']]

Upvotes: 2

Dani Mesejo
Dani Mesejo

Reputation: 61900

You could do the following:

updated_list = []
stopwords = {'is', 'a'}

articles = [['this', 'is', 'a', 'test'], ['what', 'is', 'your', 'name']]

for article in articles:
    lst = []
    for word in article:
        if word not in stopwords:
            lst.append(word)
    updated_list.append(lst)

print(updated_list)

Output

[['this', 'test'], ['what', 'your', 'name']]

But I suggest you use the following nested list comprehension, as it is considered more pythonic:

stopwords = {'is', 'a'}
articles = [['this', 'is', 'a', 'test'], ['what', 'is', 'your', 'name']]

updated_list = [[word for word in article if word not in stopwords] for article in articles]
print(updated_list)

Output

[['this', 'test'], ['what', 'your', 'name']]

Upvotes: 1

ldz
ldz

Reputation: 2215

Instead of adding the words of all articles into one list, you need to maintain separate lists for each article and finally add them to the updated_list.

Upvotes: 1

Dominik Ficek
Dominik Ficek

Reputation: 566

So you want to append list to your list if I understand your question correctly.

This should do the work:

updated_list = []
articles = list_of_articles

for article in articles:
    temp_list = list()
    for word in article:
         if word not in stopwords:
             temp_list.append(word)
    updated_list.append(temp_list)

Upvotes: 1

Related Questions