jincept
jincept

Reputation: 279

Python - too many values to unpack

I have a tuple containing string and a list of string as below:

test = ('str1',['1', '2'])
for a,b in test:
    print(a,b)

I want to unpack in a way that I can get [('str1','1'),('str1','2')].

However I am getting "ValueError: too many values to unpack (expected 2)".

If I print length of test, it comes as 2. So not sure what is wrong here.

Upvotes: 1

Views: 5889

Answers (4)

hamidfzm
hamidfzm

Reputation: 4685

You can use zip function to implement that:

>>> seq = ['1', '2']
>>> print(zip(['str']*len(seq), seq))
[('str', '1'), ('str', '2')]

Upvotes: 2

TigerhawkT3
TigerhawkT3

Reputation: 49310

"Too many values to unpack" means exactly that. Let's look at the elements in test:

test = ('str1',['1', '2'])
for a,b in test:
    print(a,b)

Each element in test will be unpacked into two variables. The first element is 'str1', and the second one is ['1', '2']. 'str1' is a string with four characters, so, unpacked, it would need four variables. However, you only provide two, a and b. That's the error.

To get the output you want, I recommend unpacking as follows:

a,b = test

Now a is 'str1', and b is ['1', '2']. You can then loop through the values in b:

for item in b:
    print(a, item)

Result:

str1 1
str1 2

Upvotes: 1

Simeon Visser
Simeon Visser

Reputation: 122376

Although test has two elements, you're attempting to iterate over tuples which won't work because test has no tuples (it's a tuple itself).

So this works:

test = [('str1',['1', '2'])]
for a,b in test:
    print(a,b)

Or, to get what you want, as a list:

print([(test[0], item) for item in test[1]])

You can also iterate in that way:

test = ('str1',['1', '2'])
for item in test[1]:
    print(test[0], item)

Upvotes: 3

Cyphase
Cyphase

Reputation: 12022

Your code iterates over each item in test; first 'str1', then ['1', '2']. The problem is when you try to do a, b = 'str1' (this is what the for loop is doing). There are 4 values in 'str1', but only two variables to which you're trying to assign them.

Here's one way to do what you actually want:

test = ('str1',['1', '2'])

test_str, test_list = test

for b in test_list:
    print(test_str, b)

In this code, test_str is 'str1' and test_list is ['1', '2']. Then you iterate over test_list, and just reference test_str to get 'str1'.

Upvotes: 0

Related Questions