One of the unique syntactic features of Python 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.
It’s worth noting that Python does not translate the syntax literally. For example, if you try this with a dictionary, it won’t work as you might expect.
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:
Incorrect! The values in random_list are strings, not lists. Try again.
’James’
Incorrect! x is listed before y in the tuple on the left side of the assignment statement, so the first value in random_list should be assigned to x. Try again.
’Harden’
Correct! This properly assigns the first element of the list to ’x’.
Both sides of this statement are tuples, but Python interprets the left side to be a tuple of variables and the right side to be a tuple of expressions. All of the expressions on the right side are evaluated before any of the assignments. This means that the values of b and a on the right side are evaluated, then a and b on the left side take on their values.
More generally, the right side can be any kind of sequence (string, list, or tuple). For example, to split an email address into a username and a domain, you could write: