+ 1

list.remove(obj) problem

Does list.remove(obj), remove all instances of obj from the list?

3rd Feb 2017, 2:59 PM
Mr. Pool
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 ^^
4th Feb 2017, 10:43 AM
visph
visph - avatar
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']
3rd Feb 2017, 3:31 PM
Kaden
Kaden - avatar
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)
3rd Feb 2017, 3:35 PM
Kaden
Kaden - avatar
0
no, as in a = ['a', 'a', 'ab', 'b' ] does remove, remove both the 'a'?
3rd Feb 2017, 3:41 PM
Mr. Pool
0
thanks
4th Feb 2017, 10:45 AM
Mr. Pool