Reputation: 13
Can anyone explain what is the problem with this code?
for game_name,game_size in games_names,games_sizes:
print(f'Game_Name = {game_name} Size = {game_size}')
This is Python code where I try to iterate over two lists and print their values but it gives me this error:
ValueError: too many values to unpack (expected 2)
Upvotes: 1
Views: 4093
Reputation: 450
If you want to iterate over 2 lists in same moment, you should use zip()
funciton.
Example:
>>> lol = [1,2,3,4,5]
>>> kek = [6,7,8,9,10]
>>> for num, secnum in zip(lol, kek):
... print(num, secnum)
Let me explain why you can't "unpack" it.
For example, lets say that we have this list:
arr = [1, 2, 3, 4, 5]
. On every iteration you can get only 1 object, right?
one = arr[0]
two = arr[2]
...
So that's how we could get values from list. We can assign values like this too:
one, two, three = arr[0], arr[1], arr[2]
In python there is *
sign, means that you could 'pack' value in list.
colors = ['cyan', 'magenta', 'yellow', 'black']
cyan, magenta, *other = colors
print(cyan)
print(magenta)
print(other)
Output:
cyan
magenta
['yellow', 'black']
Summary what unpucking do:
Upvotes: 3