How To .remove All Matches In A Python List?
If I have a bit of Python like: n = [1, 3, 5, 1] n.remove(1) print n n will return [3, 5, 1] because .remove() quits after it finds its first match. What could I do to return just
Solution 1:
If creating a new list is fine:
n = [x for x in n if x != 1]
Of course you could also use slice assignment to modify the list in place:
n[:] = [x for x in n if x != 1]
Solution 2:
use filter function
n = [1, 3, 5, 1]
filter(lambda a:a isnot1,n)
[3,5]
edit
n = [1, 3, 5, 1]
filter(lambda a:a != 1,n)
[3,5]
Solution 3:
Simple List Comprehension -
>>>n = [1, 3, 5, 1]>>>n = [e for e in n if e != 1]>>>n
[3, 5]
If you wanted to remove more than one elements -
>>>g = [1,3]>>>n = [e for e in n if e notin g]>>>n
[5]
Solution 4:
This is not how I'd normally do this, but:
n = [1, 3, 5, 1]
REMOVECHAR = 1while REMOVECHAR in n:
n.remove(REMOVECHAR)
# could also do:
# while1:
# try: n.remove(REMOVECHAR)
# except ValueError as e: break
If I were doing it, I would use a list comp to make a new list.
n = [1,3,5,1]
REMOVECHAR = 1nn = [element for element in n if element != REMOVECHAR]
Solution 5:
You could iterate backwards through the list and pop elements that match.
def remove_all_in_place(target, sequence):
cursor= len(target) -1
while cursor>=0:
if sequence[cursor] == target:
sequence.pop(cursor)
cursor-=1
List comprehensions might be faster since they are optimized, but they aren't in-place operations. For native Python implementations, I think this would be fastest, as well as being true in-place.
Post a Comment for "How To .remove All Matches In A Python List?"