Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. List, Tuples and Dictiona...
  5. Tuples
  6. Tuple Assignment

Tuple Assignment

Introduction

  • Tuple assignment allows the assignment of values to a tuple of variables on the left side of the assignment from the tuple of values on the right side of the assignment
  • The number of variables in the tuple on the left side of the assignment must match the number of elements / items in the tuple on the right of the assignment

Example

#create a tuple
>>> student=(35,"XYZ","CSE","PYTHON",99)
#tuple assignment
>>> (reg_no,name,dept,sub,mark) = student
>>> print(reg_no)
35
>>> print(name)
XYZ
>>> print(dept)
CSE
>>> print(sub)
PYTHON
>>> print(mark)
99

A tuple named student is created with 5 elements. In the next statement, the value of each element of this tuple is assigned to the respective variables

Tuple Assignment for Swapping two numbers

Swapping two numbers using temporary variables

a=int(input("Enter number 1:"))
b=int(input("Enter number 2:"))
print("Before swapping:a={0} and b ={1} ".format(a,b))
t = a
a = b
b = t
print("After swapping:a={0} and b = {1}".format(a,b))

Swapping two numbers using tuple assignment

a=int(input("Enter number 1:"))
b=int(input("Enter number 2:"))
print("Before swapping:a={0} and b ={1} ".format(a,b))
a,b = b,a
print("After swapping:a={0} and b = {1}".format(a,b))

Multiple Assignment

Multiple values can be assigned to multiple variables using tuple assignment

Example
(a,b,c)=(2,-1,10)
print("a=",a)
print("b=",b)
print("c=",c)
Output
a= 2
b= -1
c= 10

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments