My Coding > Programming language > Python > Python FAQ > Python: How to unpack the beginning of the list

Python: How to unpack the beginning of the list

If you have a list or tuple, to unpack it you can use the following expression:


LST = [1, 2, 3, 4, 5]
a, b, c, d, e = LST

The number of variables in the left part should be equal to the number of elements in the right part, otherwise, you will have an error: ValueError: too many values to unpack (expected 2)

But what should you do if you want to take only a few first values? Use star!!!


LST = [1, 2, 3, 4, 5]
a, b, *rest = LST
print(rest)
#[3, 4, 5]

In this case, a and b will be 1 and 2, respectively, and all outstanding parts of the list will go to the new list rest


Published: 2023-09-14 22:14:48
Updated: 2023-09-14 22:20:22

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.