Introduction to Python
Programming Cycle of Python
Varibles and Datatypes in Python
Input and Output in Python
Operators in Python
Precedence of Operators in Python
Typecasting in Python
If Else in Python
Loops in Python
Break, Continue and Pass in Python
Functions in Python
Default Arguments and Keyword Arguments in Python
Strings in python
Lists in Python
Tuple in Python
Dictionary in Python
Sets in Python
List Comprehension in Python
Unpacking Sequences in Python
Higher Order Functions in Python
Lambda Functions in Python
Sieve of Eratosthenes Algorithm in Python
Linear Search in Python
Binary Search in Python
Selection Sort in Python
Bubble Sort in Python
Insertion Sort in Python
Merge Sort in Python
Unpacking Sequences in Python
Unpacking means taking the values of a sequence such as a list, tuple, etc and
storing them in separate variables.
l=["Rapid", "Coders"]
r,c=l
print(r,type(r))
print(c,type(c))
Output
Rapid <class 'str'> Coders <class 'str'>
The number of variables on the left should be equal to the number of values in the iterable.
l=["Rapid", "Coders"]
r,c,d=l
print(r,c,d)
Output
ValueError: not enough values to unpack (expected 3, got 2)
Similarly, you can unpack a tuple, string, dict, etc.
t=("Excellent", "Coders")
a, b = t
print(a)
print(b)
print()
rapid="Rapid"
r,a,p,i,d=rapid
print(r,a,p,i,d)
print()
# On unpacking a dictionary, we get its keys
dic={"Good": "Coders", "Excellent": "Coders"}
g,e=dic
print(g)
print(e)
Output
Excellent Coders R a p i d Good Excellent
If you want to unpack only certain values, you can do something like -
r,_,p,_,d="Rapid"
print(r)
print(p)
print(d)
Output
R p d
If you do not want to unpack all the values as variables and store some of the values
together as a list, then you can do something like -
t=("Rapid", "Coders", "Excellent", "Coders")
*a,b,c=t
print(a,type(a))
print(b,type(b))
print(c,type(c))
print()
s="Rapid"
r,*p,d=s
print(r,type(r))
print(p,type(p))
print(d,type(d))
Output
['Rapid', 'Coders'] <class 'list'> Excellent <class 'str'> Coders <class 'str'> R <class 'str'> ['a', 'p', 'i'] <class 'list'> d <class 'str'>