Skip to main content
Engineering LibreTexts

10.3: Tuple Assignment

[ "article:topic", "authorname:severancec", "python (language)", "license:ccbyncsa" ]
  • Page ID
    3172
  • One of the unique syntactic features of the Python language is the ability to have a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time when the left side is a sequence.

    In this example we have a two-element list (which is a sequence) and assign the first and second elements of the sequence to the variables x and y in a single statement.

    >>> m = [ 'have', 'fun' ]
    >>> x, y = m
    >>> x
    'have'
    >>> y
    'fun'
    >>>

    It is not magic, Python roughly translates the tuple assignment syntax to be the following:2

    >>> m = [ 'have', 'fun' ]
    >>> x = m[0]
    >>> y = m[1]
    >>> x
    'have'
    >>> y
    'fun'
    >>>

    Stylistically when we use a tuple on the left side of the assignment statement, we omit the parentheses, but the following is an equally valid syntax:

    >>> m = [ 'have', 'fun' ]
    >>> (x, y) = m
    >>> x
    'have'
    >>> y
    'fun'
    >>>

    A particularly clever application of tuple assignment allows us to swap the values of two variables in a single statement:

    >>> a, b = b, a

    Both sides of this statement are tuples, but the left side is a tuple of variables; the right side is a tuple of expressions. Each value on the right side is assigned to its respective variable on the left side. All the expressions on the right side are evaluated before any of the assignments.

    The number of variables on the left and the number of values on the right must be the same:

     

    >>> a, b = 1, 2, 3
    ValueError: too many values to unpack

    More generally, the right side can be any kind of sequence (string, list, or tuple). For example, to split an email address into a user name and a domain, you could write:

     

    >>> addr = 'monty@python.org'
    >>> uname, domain = addr.split('@')

    The return value from split is a list with two elements; the first element is assigned to uname, the second to domain.

    >>> print(uname)
    monty
    >>> print(domain)
    python.org