Confused about formatting required for union() method arguments

Screen Link: Learn data science with Python and R projects

Solution code provided by dataquest:

def union(iter1, iter2):
    return set(iter1).union(iter2)

I’m curious why the iter2 argument in the function above does not need to be converted to a set as well. Converting iter1 to a set appears to be required, otherwise we get the following error:

Error message:

def union(iter1, iter2):
    return iter1.union(iter2)

print(set(), [1, 2])
print(union((0, 17, 1337), [2, 3, 4, 5, 6]))
print(union(range(3), "88"))

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-1-cbbf452bbbf7> in <module>
      4 
      5 print(set(), [1, 2])
----> 6 print(union((0, 17, 1337), [2, 3, 4, 5, 6]))
      7 print(union(range(3), "88"))

<ipython-input-1-cbbf452bbbf7> in union(thing1, thing2)
      1 from ac import *
      2 def union(thing1, thing2):
----> 3     return thing1.union(thing2)
      4 
      5 print(set(), [1, 2])

AttributeError: 'tuple' object has no attribute 'union'

Hi @cjouard9 and welcome to the community!

I tried to find some official documentation to help shed some light on this but I didn’t have much luck :slightly_frowning_face:

That said, I believe the answer to your question goes something like this: we need to cast the first argument of the function as a set because the union() method only works on sets and will return a set as output. The second argument (the one passed to the union() method) is probably being coerced as a set behind the scenes within the union() method. In fact, it’s likely that argument passed to union() needs only be an iterable and does not necessarily need to be a set at all.

1 Like

Thank for all the above @mathmike314! Very helpful.