Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure list contains unique elements?

Tags:

python

list

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

ClassName:
 - list_of_strings

I need to enforce that this list of strings contains unique elements. Unfortunately, I can't change this list_of_strings to another type, like a set.

In the addToList(str_to_add) function, I want to guarantee string uniqueness. How can I best do this? Would it be practical to add the string being added to the list, convert to a set, then back to a list, and then reassign that to the object?

Here's the method I need to update:

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

Thanks!

like image 650
Cuga Avatar asked Jan 20 '11 04:01

Cuga


1 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)
like image 173
ephemient Avatar answered Oct 05 '22 05:10

ephemient