0

I have a list of lists as follows.

mylist = [["i", "love", "to", "eat", "tim tam"], ["tim tam", "is", "my", "favourite", 
"chocolate", "and", "i", "eat", "it", "everyday"]]

I also have a list namely stops as below.

stops = ["and", "the", "up" "to", "is", "i", "it"]

Now, I want to search through mylist and remove the aforementioned stops from it. Hence, my final mylist will look as below.

mylist = [["love", "eat", "tim tam"], ["tim tam", "my", "favourite", "chocolate", "eat", "everyday"]]

My current code is as follows.

for k in mylist:
    for item in k:
        if k in stops:
            pop(k)

It gives me TypeError: unhashable type: 'list'. Please help me.

2 Answers2

1

Brute force Solution:

mylist = [["i", "love", "to", "eat", "tim tam"], ["tim tam", "is", "my", "favourite", 
"chocolate", "and", "i", "eat", "it", "everyday"]]

stops = ["and", "the", "up","to", "is", "i", "it"]

for currlist in mylist:
    for i in stops:
        if i in currlist:
            currlist.remove(i)

print(mylist)

Hope this Helps!

Rehan Shikkalgar
  • 1,029
  • 8
  • 16
  • The answer has already been mentioned [here](https://stackoverflow.com/questions/47068199/search-an-element-in-a-list-and-remove-it-in-python?noredirect=1#comment81084357_47068199). Does your answer add anything substantial over it besides a copy-paste of the code? – cs95 Nov 02 '17 at 05:36
  • it should be; `for currlist in mylist: for i in currlist: if i in stops:` right? :) –  Nov 02 '17 at 05:40
  • @Volka even that will work fine – Rehan Shikkalgar Nov 02 '17 at 05:47
  • 1
    @COLDSPEED check the link which you have mentioned, it is link of this question itself. please verify – Rehan Shikkalgar Nov 02 '17 at 05:49
0

The easiest way is to create a new list that contains the result:

[[i for i in s if i not in stops] for s in mylist]

A more efficient way to do this is to create a set out of stops, making the membership test faster:

stops_set = set(stops)
[[i for i in s if i not in stops_set] for s in mylist]
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41