Search code examples
pythonsetnamedtuplepython-collections

python set union operation is not behaving well with named tuples


I want to create a set of namedtuple in python, with the ability to add elements dynamically using the union operation.

The following code snippet creates a set of namedtuple, which is behaving nicely.

from collections import namedtuple

B = namedtuple('B', 'name x')

b1 = B('b1',90)
b2 = B('b2',92)
s = set([b1,b2])
print(s)

which prints

{B(name='b1', x=90), B(name='b2', x=92)}

Now if I create another namedtuple and add it to my set with the union operations it is not behaving as expected.

b3 = B('b3',93)
s = s.union(b3)
print(s)

The code snippet prints the following output.

{93, B(name='b1', x=90), B(name='b2', x=92), 'b3'}

The expected output should be:

{B(name='b1', x=90), B(name='b2', x=92), B(name='b3', x=93)}

Am I mis-understanding the API? Both python2 and 3 are showing the same behaviour.


Solution

  • union expects a set (or a list or another iterable), but you pass a named tuple, which is an iterable by itself, but it provides values, so you merge the set with the values. Try this:

    s = s.union({b3})