Its_FZX
Its_FZX

Reputation: 13

ValueError: too many values to unpack (expected 2) when trying to iterate over twolists at the same time

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

Answers (1)

r1v3n
r1v3n

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:

  1. Unpacking assigns elements of the list to multiple variables.
  2. Use the asterisk (*) in front of a variable like this *variable_name to pack the leftover elements of a list into another list.

Upvotes: 3

Related Questions