0

Consider the following in Python

>>> my_set = set( (((((1,2))))) )                                                                                                                                                                                                                                                                                                                                       
>>> my_set
{1, 2}


>>> my_obj = (((((1,2)))))
>>> type(my_obj)
tuple

I am perplexed by this behavior. My understanding is that set expects an iterable, and a tuple is an iterable, so shouldn't my_set be initialized with the first element in (((((1,2))))), i.e. ((((1,2)))), instead of with the values 1 and 2?

Josh
  • 11,979
  • 17
  • 60
  • 96
  • 3
    Adding extra parentheses does not make an expression a tuple. You also need a comma: `(((((1,2),),),),)`. – DYZ Aug 02 '20 at 00:49
  • Thanks @DYZ, and if so, why is `my_obj` in my example above a tuple? – Josh Aug 02 '20 at 00:51
  • 3
    Because `(1,2)` is a two-element tuple, no matter how many parentheses you wrap around it. – DYZ Aug 02 '20 at 00:53
  • 3
    Because `(((((1,2)))))` means the same thing as `(1, 2)`. The innermost pair of parentheses has a comma inside it, after all - it's only all the *others* that are just expression-grouping parentheses. We say that "the comma makes the tuple, not the parentheses" - and you *do have a comma*. – Karl Knechtel Aug 02 '20 at 00:53

0 Answers0