Tuple assignment

Tuples have unique syntactic features in Python programming language and that is the ability to have a tuple on the left hand side of an assignment statement. This allows you to assign more than one variable at a time when the left hand side is a sequence.
In this example we have a two element list (this is a sequence) and assign the first and second elements of the list to variables x and y in a single statement.
a = [‘Python’, ‘language’]
x,y = a 
print x 
print y 
Output of previous script is given below.
Python 
language 
Python translates the tuple assignment to be the following
a = [‘Python’, ‘language’]
x = a[0]
y = a[1]
print x 
print y 
Output is the same as in previous example. When we use a tuple on the left hand side of the assignment statement, we omit the parentheses, but the following is an equally valid syntax:
a = [‘Python’, ‘language’]
(x,y) = a
print x 
print y 
A particularly clever application of tuple assignment allows us to swap the values of two variables in a single statement.
x,y = y,x
In previous example both statements are tuples, but the left side is a tuple of variables while 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 have to be the same otherwise you’ll get ValueError.
a, b = 1,2,3
Traceback (most recent call last):
  File "", line 1, in 
ValueError: too many values to unpack

Nema komentara:

Objavi komentar