First of all, using a list comprehension only for its side effects is a bad practice. You should use
lst = [x for x in lst if x <= 2]
Additionally, don't use list
as a variable name, because it is already taken by the builtin list. Third of all, your approach is not working because you are iterating over your list while mutating it.
Here's a demo of what's happening with your approach:
# python interpreter
>>> lst = [1,2,3,4]
>>> for item in lst:
... print(item)
... if item > 2:
... lst.remove(item)
... print(lst)
...
1
[1, 2, 3, 4]
2
[1, 2, 3, 4]
3
[1, 2, 4]
As you can see, item
is never 4
.
As for your second question:
Also, what I'm trying to do is remove items from listA
if item found in listB
. How can I do this with list comprehension?
bset = set(listB)
listA = [x for x in listA if x not in bset]
As for your third question:
>>> list1=['prefix1hello', 'foo', 'prefix2hello', 'hello']
>>> prefixes=['prefix1', 'prefix2']
>>> [x for x in list1 if not any(x.startswith(prefix) for prefix in prefixes)]
['foo', 'hello']
Please stop adding new questions now, you can open a new question for a different problem, thanks.