Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Variables, Expression and...
  5. Tuple Assignment

Tuple Assignment

Tuples

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. The left side is a tuple of variables, the right side is a tuple of values

Each value is assigned to its respective variable. The number of variables on the left must be same as that of number of values on the right

>>> (x,y,z) = "python","chemistry","physics"
>>> x
'python'
>>> y
'chemistry'
>>> z
'physics'

Example

Swapping two numbers in conventional method

a = 10
b = 20
print("Before Swapping")
print("a=",a)
print("b=",b)
temp = a
a=b
b=temp
print("After Swapping")
print("a=",a)
print("b=",b)

Swapping two numbers using Tuple Assignment

a = 10
b = 20
print("Before Swapping")
print("a=",a)
print("b=",b)
(a,b) = (b,a)
print("After Swapping")
print("a=",a)
print("b=",b)
Output
Before Swapping
('a=', 10)
('b=', 20)

After Swapping
('a=', 20)
('b=', 10)

Tuple Packing

  • In tuple packing, the values on the left are packed together in a tuple
  • Example
>>> tuple1 = (1,"ABC", 100)
>>> tuple1
(1, 'ABC', 100)

Tuple Unpacking

In tuple unpacking, the values in a tuple on the right are unpacked into the variable / names on the right

Example

>>> (register_num,name, mark)=tuple1
>>> register_num
1
>>> name
'ABC'
>>> mark
100
>>>

The right side can be any kind of sequence (string, list, tuple)

Loading

Views: 15

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments