What is tuple unpacking in Python?

ProgrammingPython

Before defining tuple unpacking we need to understand what is tuple.

Tuple : In Python tuples are used to store immutable object.A tuple is a sequence of immutable Python objects. Tuples are sequences, the tuples cannot be changed and tuples use parentheses. it assigns (RHS)right hand side of values into (LHS)Left hand side. In other way it is called unpacking of a tuple of values into a variable. In unpacking of tuple number of variables on LHS should be equal to number of values in given tuple. In packing, we put values into a new tuple while in unpacking we extract those values into a single variable.

Example 1

tuple = ("Tutorials Point", 132, "Employees") # tuple packing
(companyname , Employerscount ,Information) = tuple # tuple unpacking
print(companyname)
print(Employerscount)
print(Information)

Output

Tutorials Point
132
Employees

Example 2

tuple = ("RRS College of Engg and Technology", 6000, "Engineering") # tuple packing
(college, student, graduates) = tuple # tuple unpacking
# print college name
print(college)
# print no of student
print(student)
# print type of college
print(graduates)

Output

RRS College of Engg and Technology
6000
Engineering
raja
Sri
Published on 27-Jun-2019 18:55:16
Advertisements