
Python Tuple Syntax Is Confusing - joaofcosta
http://dino.codes/posts/python-tuple-syntax-is-confusing/
======
eesmith
The tuple notation is one of those places where the obvious way is a
distraction. A non-empty tuple doesn't need the ()s - it's the "," which makes
the tuple! The following two are equivalent:

    
    
      x = 1,
      x = (1,)
    

so are the following three:

    
    
      y = 1, 2, 3
      y = 1, 2, 3,
      y = (1, 2, 3)
    

Of course, then there's no way to express the empty tuple using commas, which
is where () comes in.

~~~
joaofcosta
Thanks for reminding me tuples can be instantiated without the use of
parenthesis, that's something I usually forget about.

I'm much more used to only using commas when extracting values from a tuple,
for example:

    
    
        a, b, c = (1, 2, 3)
    

I think maybe the only "issue" with the syntax where no parenthesis is used is
that, as obvious as it may seem, you can't use it when passing parameters to
function. For example:

    
    
        # Will work
        function(parameter, (1,2,3))
    
        # Won't work
        function(parameter, 1, 2, 3)
    

Not really an issue but just nice to know that it doesn't work on every
scenario.

Anyway, nice to be reminded of other options :)

~~~
eesmith
Tuples and generator comprehensions also don't mix well:

    
    
      >>> (x, x*2 for x in "qwe")
        File "<stdin>", line 1
          (x, x*2 for x in "qwe")
                  ^
      SyntaxError: invalid syntax
    
      >>> ((x, x*2) for x in "qwe")
      <generator object <genexpr> at 0x107821350>

