Loop Control Statements in C Introduction to HTML How to use the Github API The image tag, anchor tag and the button tag Ordered and Unordered Lists in HTML The division tag HTML Forms Tables in HTML Introduction to C Programming Introduction to Python Varibles and Datatypes in Python Operators in Python Typecasting in Python Input and Output in Python If Else in Python Loops in Python Break, Continue and Pass in Python Python practice section 1 Lists in Python Tuple 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'>