Unpacking a list in Python

Unpacking  of list in Python : 

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

Example :

  • ( a, b, c ) = list_name.
list in python

List : 

list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item.

Unpacking a list in Python

Code 1 :

Run
# Program to understand about 
# packing and unpacking in Python
# this lines PACKS values
# into variable a as list 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 List in Python) which simplifies our work. 
  • Python uses a special syntax to pass optional arguments (*args) for List 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
# 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=list(map(int,input().split()))
print('The given List: ',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) 

Output : 

The given List: [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