Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a "too many values to unpack" value error

Tags:

python

I've looked at other answers but it looks like they use 2 different values.

The code:

user = ['X', 'Y', 'Z']
info = [['a','b','c',], ['d','e','f'], ['g','h','i']]

for u, g in user, range(len(user)):
    print '|',u,'|',info[g][0],'|',info[g][1],'|',info[g][2],'| \n'

So basically, it needs to output:

'| X | a | b | c |'
'| Y | d | e | f |'
'| z | g | h | i |'

But instead, I get this error:

Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    for u, g in user, range(len(user)):
ValueError: too many values to unpack

As far as I know both user and range(len(user)) are of equal value.

like image 634
user2374668 Avatar asked Dec 02 '22 22:12

user2374668


1 Answers

for u,g  in user, range(len(user)):

is actually equivalent to:

for u,g  in (user, range(len(user))):

i.e a tuple. It first returns the user list and then range. As the number of items present in user are 3 and on LHS you've just two variable (u,b), so you're going to get that error.

>>> u,g = user
Traceback (most recent call last):
  File "<ipython-input-162-022ea4a14c62>", line 1, in <module>
    u,g = user
ValueError: too many values to unpack

You're looking for zip here(and use string formatting instead of manual concatenation):

>>> user = ['X', 'Y', 'Z']
>>> info = [['a','b','c',], ['d','e','f'], ['g','h','i']]
for u, g in zip(user, info):
    print "| {} | {} |".format(u," | ".join(g))
...     
| X | a | b | c |
| Y | d | e | f |
| Z | g | h | i |
like image 63
Ashwini Chaudhary Avatar answered Dec 09 '22 14:12

Ashwini Chaudhary