Iterable or value Unpacking
Iterable or value unpacking allows to assign various variables on the left the values from an iterable or simply multiple values mentioned.
Traditional Way
Python3
# Iterable unpacking (list unpacking to be specific) a, b, c = [ 1 , 2 , 3 ] print (a, b, c) # output (1 2 3) |
One Liner
Python3
# Packing values with * operator a, * b, c = [ 1 , 2 , 3 , 4 , 5 ] print (a) # 1 print (b) # [2, 3, 4] print (c) # 5 |
Here, it is mandatory to assign values to a and c therefore, the values left for b are 2, 3 and 4.
ValueError while Unpacking
Python3
a, * b, c, d = [ 1 , 2 , 3 ] print (a) # 1 print (b) # [] print (c) # 2 print (d) # 3 |
Here, b is empty because it is mandatory to assign values to a, c, and d.
While the below code would give an error because of not having sufficient values to assign to a, c, d, and e.
Python3
a, * b, c, d, e = [ 1 , 2 , 3 ] |
ValueError: not enough values to unpack (expected at least 4, got 3)
10 Useful Python One Liners That Developers Must Know
Python is known for its easy-to-code and intuitive syntax. And one-liners are like the cherry on the cake which makes Python a more beautiful and beloved programming language. There are numerous features in Python Language and one of its most loved features is its one-liners. Writing Code in Python is already easy compared to other programming languages and using the one-liners makes it more easier and cool. Now let’s see what are these Python one-liners.
Contact Us