Cuga
Cuga

Reputation: 17904

How to ensure list contains unique elements?

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!

Upvotes: 8

Views: 31167

Answers (5)

Walker
Walker

Reputation: 1

Perhaps we can do like 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 whether it's the same mechanism with if/else yet.

Upvotes: 0

void-pointer
void-pointer

Reputation: 14827

One possible way to do this would be to create a hash set and iterate through the list, adding the elements to the set; a second iteration could be used to remove any duplicates.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

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

Upvotes: 4

icktoofay
icktoofay

Reputation: 129011

You indeed could do the list-to-set-to-list operation you described, but you could also use the in operator to check if the element is already in the list before appending it.

Upvotes: 1

ephemient
ephemient

Reputation: 204758

def addToList(self, str_to_add):
    if str_to_add not in self.list_of_strings:
        self.list_of_strings.append(str_to_add)

Upvotes: 21

Related Questions