+ 4
Is there a method which removes all of the same elements from a list at once in python?
For example, list = ["a", "b", "c", "b", "b", "d"] How can I remove all of the "b"s? The easiest way I can think of, for now, is list = ["a", "b", "c", "b", "b", "d"] new_list = [x for x in list if x != "b"] Is there a method or a better way than this one? (I searched for similar questions, but I couldn't find any...I'm sorry if this is duplicated.)
11 Respostas
+ 6
Here an solution that might help you
let's say alice is your list
list(filter(("b").__ne__,alice))
+ 4
Thank you for answering.
But in your way, one "b" still remains.
And if the list is
list = ["a", "b", "c", "b", "c"] ,
then one "c" is also removed.
I don't want other elements to be removed if they are duplicated.
+ 4
It's ok. Thank you for answering anywayđ
+ 4
It a rich comparison method
In this , a!=b is written as a.__ne__(b)
+ 4
I understoodâš Thank you very much for your helpđ
+ 3
Thank you very muchđ It worked!
What is .__ne__?
+ 3
Bebida Roja
Thank you for answering.
But in your way, one "b" still remains.
And if the list is
list = ["a", "b", "c", "b", "c"] ,
then one "c" is also removed.
I don't want other elements to be removed if they are duplicated.
+ 2
There's a trick
Say x is your list
print(list(set(x)))
+ 2
Welcome
+ 2
just convert the list to a set, although you will have an unordered set.
+ 1
Ahhh....sorry ways on the way to home...didn't read your question properly
Thought just need to remove duplicates