-3

I have a list that contains elements and want to delete some elements that has particular keyword.

For example:

List contains: list = ['red rose','blue rose','red color','yellow paper']

And I'm looking for deleting lists with keyword 'RED' and get output as

Output: ['blue rose', 'yellow paper']

Thank you.

Sai Kiran
  • 37
  • 5

4 Answers4

0

There are primarily two ways of doing this:

Using list comprehension:

lst = ['red rose', 'blue rose', 'red color', 'yellow paper']

output = [i for i in lst if 'red' not in i.lower()]

Using a for loop:

lst = ['red rose', 'blue rose', 'red color', 'yellow paper']

output = []
for i in lst:
    if 'red' not in i.lower():
        output.append(i)

Hope that helps!

Zilong Li
  • 889
  • 10
  • 23
0
list = ['red rose','blue rose','red color','yellow paper']
keyword = 'RED'
for i in list[:]:
    if i.find(keyword.lower()) != -1:
        list.remove(i)
print(list)
  • 1) Do not use the name of [built-in functions](https://docs.python.org/3/library/functions.html) as a variable name. Just try `print(list("ABCD"))` at the end of your code to see, what I mean. 2) Do not delete list elements while iterating over it. Try your script with `['red rose','blue rose','red color', 'red ridignhood', 'yellow paper']` to illustrate the problem. 3) Please consider adding a description, when posting an answer. I suggest reading [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) – Mr. T May 11 '18 at 06:17
-1

All what you need is a loop:

s =  ['red rose','blue rose','red color','yellow paper']
s = [x for x in s if not str(x).lower().__contains__('red')]
print(s)

['blue rose', 'yellow paper']

Minions
  • 5,104
  • 5
  • 50
  • 91
-1
>>> foo = ['red rose','blue rose','red color','yellow paper']

>>> [x for x in foo if 'red' not in x]
['blue rose', 'yellow paper']

This of course assumes lower case letters. And note it doesn't delete entries, but rather creates a new list object.

BoltzmannBrain
  • 5,082
  • 11
  • 46
  • 79