Search code examples
pythonsetadditiondata-consistency

What is the best practice to add tuples to a set?


Consider this example:

In [44]: exl_set = set(a.node)
In [45]: exl_set 
Out[45]: set(['1456030', '-9221969'])
In [46]: exl_set.add(b.node)
In [47]: exl_set
Out[47]: set(['1456030', ('-9227619', '1458170'), '-9221969'])

What is the best way to add tuples of length 2 to a set without breaking them apart with the first add? The result should look like this:

Out[48]: set([ ('-9221969','1456030'),('-9227619', '1458170')])

Solution

  • Wrap your initial node in list or tuple:

    exl_set = set([a.node])
    

    to not have it interpreted as a sequence of values.

    The set() constructor interprets the argument as an iterable and will take all values in that iterable to add to the set; from the documentation:

    class set([iterable]):
    Return a new set or frozenset object whose elements are taken from iterable.

    Demo:

    >>> node = ('1456030', '-9221969')
    >>> set(node)
    set(['1456030', '-9221969'])
    >>> set([node])
    set([('1456030', '-9221969')])
    >>> len(set([node]))
    1
    

    Alternatively, create an empty set and use set.add() exclusively:

    exl_set = set()
    exl_set.add(a.node)
    exl_set.add(b.node)