TUPLE
ASSIGNMENT
v An assignment to all of the elements in a
tuple using a single assignment statement.
v Python has a very powerful tuple assignment feature that allows a tuple of variables on the left of an assignment to be assigned values from a tuple on the right of the assignment.
v The left side is a tuple of variables; the
right side is a tuple of values.
v Each value is assigned to its respective
variable.
v All the expressions on the right side are
evaluated before any of the assignments. This feature makes tuple assignment
quite versatile.
v Naturally, the number of variables on the left
and the number of values on the right have to be the same.
>>>
(a,
b, c, d) = (1, 2, 3)
ValueError:
need more than 3 values to unpack
-It is useful to
swap the values of two variables. With conventional
assignment statements, we have
to use a temporary variable. For example, to swap a and b:
a=2;b=3
print(a,b)
temp = a
a = b
b = temp
print(a,b)
(2, 3)
(3, 2)
>>>
-Tuple
assignment solves this problem neatly:
(a, b) = (b, a)
-One way to think of tuple assignment is as
tuple packing/unpacking.
In tuple
packing, the values on the left are ‘packed’ together in a tuple:
>>> b =
("George", 25, "20000") # tuple packing
-In tuple
unpacking, the values in a tuple on
the right are ‘unpacked’ into
the variables/names on the
right:
>>> b =
("George", 25, "20000") #
tuple packing
>>> (name, age, salary)
= b # tuple unpacking
>>>
name
'George'
>>>
age
25
>>>
salary
'20000'
-The right side
can be any kind of sequence (string,list,tuple)
-To split an
email address in to user name and a domain
>>>
mailid='god@abc.org'
>>> name,domain=mailid.split('@')
>>>
print name
god
print (domain)
abc.org
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.