-2

Say I have a list:

my_list = ["A", "B", "haha_test_haha", "C"]

I want to remove any and all elements that hold the substring test.

Output:

my_list = ["A", "B", "C"]

I've been trying list comprehensions with no luck. This would be the desired solution.

Note: I need only test to be removed. Not a list of words to remove.


My attempt:

my_list = ['A', 'B', 'C', 'C', 'ahahtestaagaga']

my_list = [remove for e in my_list if e.substring('test')]

print([sa for sa in a if not any(sb in sa for sb in b)])
  • 2
    Please show the list comprehension you tried. And explain what happened. Show some output and explain what you want your code to do differently. – Code-Apprentice Apr 01 '21 at 16:37
  • 1
    Possible duplicate: https://stackoverflow.com/questions/24442091/list-comprehension-with-condition – Aaron Apr 01 '21 at 16:39
  • I will append attempt to post. Sorry for downvotes. Forgot minimal code example –  Apr 01 '21 at 16:40
  • 1
    `e.substring('test')`? Why are you trying to use `e.substring`? Are you asking how to check if a string is a substring of another? You attempts really don't make any sense. – juanpa.arrivillaga Apr 01 '21 at 16:49
  • @juanpa.arrivillaga I wasn't sure on what I was trying to use, admittedly. My desired solution was a list-comprehension, which has since been provided. 'not in' means less function use, which is great for me who is learning. –  Apr 01 '21 at 16:53

2 Answers2

0
my_list = [word for word in my_list if 'test' not in word]
artas2357
  • 153
  • 6
  • While this code may answer the question, providing additional context regarding *how* and/or *why* it solves the problem would improve the answer's long-term value. – Sven Eberth Sep 08 '21 at 00:16
0

Think about what it would look like as a for loop, so for the sake of the example, let's build a new list (even though it's inefficient), you want to capture things that don't have "test" as a substring:

new_list = []
for x in my_list:
    if "test" not in x:
        new_list.append(x)

So what would that look like as a comprehension?

my_list = [x for x in my_list if "test" not in x]
will-hedges
  • 1,254
  • 1
  • 9
  • 18