+ 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.)

5th Dec 2018, 4:41 PM
Alice
11 Antworten
+ 6
Here an solution that might help you let's say alice is your list list(filter(("b").__ne__,alice))
5th Dec 2018, 5:09 PM
Rishi Anand
Rishi Anand - avatar
+ 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.
5th Dec 2018, 4:54 PM
Alice
+ 4
It's ok. Thank you for answering anyway😊
5th Dec 2018, 4:59 PM
Alice
+ 4
It a rich comparison method In this , a!=b is written as a.__ne__(b)
5th Dec 2018, 5:21 PM
Rishi Anand
Rishi Anand - avatar
+ 4
I understood✨ Thank you very much for your help😊
5th Dec 2018, 5:25 PM
Alice
+ 3
Thank you very much😄 It worked! What is .__ne__?
5th Dec 2018, 5:16 PM
Alice
+ 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.
6th Dec 2018, 7:40 AM
Alice
+ 2
There's a trick Say x is your list print(list(set(x)))
5th Dec 2018, 4:44 PM
Rishi Anand
Rishi Anand - avatar
+ 2
Welcome
5th Dec 2018, 5:31 PM
Rishi Anand
Rishi Anand - avatar
+ 2
just convert the list to a set, although you will have an unordered set.
5th Dec 2018, 5:48 PM
Bebida Roja
Bebida Roja - avatar
+ 1
Ahhh....sorry ways on the way to home...didn't read your question properly Thought just need to remove duplicates
5th Dec 2018, 4:56 PM
Rishi Anand
Rishi Anand - avatar