How to ensure the list contains unique elements?

I have a class containing a list of strings. Say:

ClassName: - list_of_strings 

I need to ensure that this list of strings contains unique elements. Unfortunately, I cannot change this list_of_strings to another type, for example, to a set.

In the addToList(str_to_add) function, I want to guarantee the uniqueness of the strings. How can i do this? Would it be advisable to add the line to be added to the list, convert to a set, then return to the list and then reassign it to the object?

Here I need to update the method:

 def addToList(self, str_to_add): self.list_of_strings.append(str_to_add) 

Thanks!

+7
source share
5 answers
 def addToList(self, str_to_add): if str_to_add not in self.list_of_strings: self.list_of_strings.append(str_to_add) 
+21
source

Either check for the presence of a string in the list with in , or use set in parallel, which you can check and add.

+4
source

You could indeed perform the list-to-list operation described, but you can also use the in operator to check if an item is in the list before adding it.

+1
source

One possible way to do this is to create a hash set and iterate through the list by adding items to the set; the second iteration can be used to remove any duplicates.

0
source

Perhaps we can do this:

def addToList (self, str_to_add):

 try: self.list_of_strings.index(str_to_add) except: self.list_of_strings.append(str_to_add) 

Well, I don't know if the same mechanism was with if / else yet.

0
source

All Articles