Python: Cool Tricks with the unary * Operator (2024)

  •     (*my_list,) # = (1, 2, 3), note the comma to ensure it's a tuple!
    
    This is off the original topic a bit, but it deserves a bit of elaboration.

    There's a saying in Python circles that "the comma makes the tuple". Grammatically, () are just grouping parentheses. With simple values, (foo) is just foo while (foo,) is a tuple containing foo (a common gotcha; see e.g. https://stackoverflow.com/questions/12876177). But (*my_list) would actually be a syntax error. Whereas the parentheses aren't necessary for this expression by itself:

        >>> *my_list,
        (1, 2, 3)
    
    The problem is that it's basically impossible to use this sort of tuple expression - even if a star isn't involved - as part of anything more complex without parentheses:

        >>> 1, + ()
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: bad operand type for unary +: 'tuple'
        >>> () + 1,
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: can only concatenate tuple (not "int") to tuple
        >>> 1,[0] # doesn't index into the singleton tuple
        (1, [0])
    
    The comma has very low precedence, which is fixed by adding parentheses:

        >>> 1,*3
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: Value after * must be an iterable, not int
        >>> (1,)*3
        (1, 1, 1)*