Unpacking a Tuple in Python

Unpacking a Tuple in Python:

In Python, there is a feature of the tuple that assigns the right-hand side values to the left-hand side. In another way, it is called unpacking of a tuple in Python. In packing, we put values into a new tuple while in unpacking we extract those values into a single variable. 

Example :

  • ( a, b, c ) = tuple_name.
tuples in python

Tuples : 

Tuples in a python are nothing just a list in Python. Tuples posses same property as list except for one thing which is it is not mutable and instead of square brackets, it is represented using Parenthesis.  

Unpacking a Tuple in Python

Code 1 :

Run
#Python Program 
# Program to understand about 
# packing and unpacking in Python
# this lines PACKS values
# into variable a as tuple type

a = ("Hi", 999, "Prepsters") 

# this lines UNPACKS values
# of variable a

(wel_w, num, org) = a 
print(wel_w)
print(num)
print(org)

Output : 

Hi
999
Prepsters
  • Sometimes there are n numbers of input in one line, which contains one or more variable at any end and an array of number or string. Here we can use this property (Unpacking a tuple in Python) which simplifies our work. 
  • Python uses a special syntax to pass optional arguments (*args) for tuple unpacking. This means that there can be any numbers of arguments in place of (*args). We can use any variable name in place of “*args”.

Code 2 :

Run
#Python Program 
# Program to understand about 
# packing and unpacking in Python
#any number of input let's say it contains number in array , then array and then maximum value of array 

ax=tuple(map(int,input().split()))
print('The given Tuple: ',ax)

#n will be size of array *a will be the array and c will be the maximum of array 
#value of at index 0 will be assigned to n and value at last index of ax will be assigned to c and rest will be assigned to a
#type of a will be list

n,*a,c=ax
print('The size of array: ',n) 
print('array: ',a)
print('Max of the array: ',c)

Input :

4 5 4 2 7 7

Output :

The given Tuple: (4, 5, 4, 2, 7, 7)
The size of array: 4
array: [5, 4, 2, 7]
Max of the array: 7

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription