Simplicity Simplicity - 2 years ago 56
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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download