Home | | Problem Solving and Python Programming | Tuple Assignment - Python

Chapter: Problem Solving and Python Programming : Data, Expressions, Statements

Tuple Assignment - Python

An assignment to all of the elements in a tuple using a single assignment statement.

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

 

Example:

-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:

 

Swap two numbers

a=2;b=3

print(a,b)

temp = a

a = b

b = temp

print(a,b)

Output:

(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)


Example:

-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

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Problem Solving and Python Programming : Data, Expressions, Statements : Tuple Assignment - Python |

Related Topics

Problem Solving and Python Programming : Data, Expressions, Statements


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.