3

I'm trying to extract the first three items from numbers, 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 "test.py", line 2, in <module>
    [first_item, second_item, third_item] = numbers
ValueError: too many values to unpack
miradulo
  • 28,857
  • 6
  • 80
  • 93
Simplicity
  • 47,404
  • 98
  • 256
  • 385

3 Answers3

8

You don't assign to them in a list like that, and you need to handle the rest of the unpacking for your list - your error message is indicating that there are more values to unpack than you have variables to assign to. One way you can amend this is by assigning the remaining elements in your list to a rest variable with the * unpacking operator

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

Note that this is only possible since Python 3, see PEP 3132 - Extended Iterable Unpacking,

miradulo
  • 28,857
  • 6
  • 80
  • 93
  • 1
    I like this actually better than the slicing I proposed, because the OP could add a 4th term on the left side w/o changing the code to the right of the equal sign (performance aside). – roadrunner66 May 22 '16 at 16:34
7

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

minocha
  • 1,043
  • 1
  • 12
  • 26
4

You are assigning a list of 10 numbers to 3 numbers, which is ambiguous. Slicing will help:

a,b,c = numbers[:3]
roadrunner66
  • 7,772
  • 4
  • 32
  • 38