+ 1
list.remove(obj) problem
Does list.remove(obj), remove all instances of obj from the list?
5 Réponses
+ 6
It's only remove the first occurence found...
To remove all corresponding elements, you need to iterate over. For example:
arr = [ 'a', 'a', 'ab', 'b']
while ( 'a' in arr ):
arr.remove('a')
print(arr)
output:
[ 'ab', 'b' ]
You can do more complex tests/changes by iterate over all each elements, maybe using map() method and/or list comprehension ^^
0
Yes and no, here's an example:
a = ['a', 'ab', 'ba', 'b']
a.remove('a')
print(a)
The output would be:
['ab', 'ba', 'b']
0
Here's how to remove every instance of a:
a = ['a', 'ab', 'ba', 'b']
a = (" ").join(a) #converts list 'a' to a string
a = a.replace("a", "") #replaces a with empty string
a = a.split(" ") #coverts string 'a' to a list with each object beginning at a space
a.remove("") #removes all empty strings
print(a)
0
no, as in a = ['a', 'a', 'ab', 'b' ]
does remove, remove both the 'a'?
0
thanks