Simplicity Simplicity - 1 year ago 47
Python Question

Extracting items from a list and assigning them to variables

I'm trying to extract the first three items from

, and assign them to three different variables, as follows:

numbers = [1,2,3,4,5,7,8,9,10]
[first_item, second_item, third_item] = numbers

Why am I getting this error?

Traceback (most recent call last):
File "", line 2, in <module>
[first_item, second_item, third_item] = numbers
ValueError: too many values to unpack

Answer Source

the correct way is -

[first_item, second_item, third_item] = numbers[:3]

since you are looking for only assigning the first three elements, the error comes because the other elements in the list account for the inequality on both sides of assignment