0

i have list

my_list = ['Cat Dog Tiger Lion', 'Elephant Crocodile Monkey', 'Pantera Cat Eagle Hamster']

i need to delete all of elements which containing sub = 'Cat'

so i need to have output

['Elephant Crocodile Monkey']

i think i need to do something with regex, maybe re.compile to find this values and then drop them from my_list?

i have been tryed:

for string in my_list:
    if string.find(sub) is not -1:
        print("this string have our sub")
    else:
        print("sthis string doesnt have our sub")

but i dont know how to combine it with delete this rows from my_list

2 Answers 2

2

To filter lists, a simple approach is to use a list comprehension:

[i for i in my_list if 'Cat' not in i]
# ['Elephant Crocodile Monkey']

Which is equivalent to:

out = []
for i in my_list:
    if 'Cat' not in i:
        out.append(i)
Sign up to request clarification or add additional context in comments.

1 Comment

Nice @yatu. Would this als cater for Cat being a substring though? I am keen to learn on how you would adapt your answer to make it work when Cat would be a substring of Caterpillar. I've added an answer myself but I feel that it can be done much simpler.
2

Here's your list:

my_list = ['Cat Dog Tiger Lion', 'Elephant Crocodile Monkey', 'Pantera Cat Eagle Hamster']

You can use list comprehension for filtering the list:

new_list = [x for x in my_list if(not x.__contains__('Cat'))]

2 Comments

For learning purposes. Could you explain the main differences between not in as per @yatu his answer and your not contains method?
The in keyword calls the __contains__ method of the object. I realize that in is more preferable as it is easier than method-call syntax. However, both of them give the same result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.