Skip to content Skip to sidebar Skip to footer

Python Union Of Sets Raises Typeerror

Consider a sequence of sets: >>> [{n, 2*n} for n in range(5)] [{0}, {1, 2}, {2, 4}, {3, 6}, {8, 4}] Passing them directly into the union method yields the correct result:

Solution 1:

The reason for this error is that set.union() expects one or more sets (ie set.union(oneset, anotherset, andathirdone)), not a list nor generator.

The solution is to unpack your list or generator:

>>> set().union( *({n, 2*n} for n in range(5)) )
{0, 1, 2, 3, 4, 6, 8}

Solution 2:

Here's way to union multiple sets without creating a list

s = set()

for n inrange(5): 
    s = s.union({n, 2*n})

Post a Comment for "Python Union Of Sets Raises Typeerror"