Question

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')])
Was it helpful?

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)

OTHER TIPS

When you initialize the set, the argument is treated as an iterable, not as a single item. You can do it like that:

    >>>node = (1, 3)
    >>>node_set = set([node,]) #  initialize a set with a single ilement
    >>>node_set
    set([(1, 3)])

or alternatively:

    >>>node = (1, 4)
    >>>node_set = set()  # initialize an empty set
    >>>node_set.add(node)  # add a single element
    >>>node_set
    set([(1, 4)])

To update this answer for other time travellers, another method is to use a set literal, which saves on the unnecessary wrap/unwrap process of the previous answers:

node = (1, 2)
n_set = {node}
n_set

Out[17]: {(1, 2)}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top