mardi 27 août 2019

Adding an unique item to a set

The syntax for checking if an item is already in a list and then adding it to the list if it is not is:

foo = []
if item in foo:
    foo.append(item)
    # do something

This syntax seems to duplicate the logic of a set datatype in python, yet the following syntax does not exist;

bar = set()
if bar.add(item):
    # do something

but add() returns nothing, so this is not possible. Is there a good workaround to be able to keep using a set?

Note: the reason a set is desired is the operation of adding a unique value to a set is of O(1), whereas the same operation is O(n) on a list.

Aucun commentaire:

Enregistrer un commentaire