4

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.

1
  • 3
    Aside: If you really do want a list and its indexes, try: for g,u in enumerate(user):. But, as others have said, in this case you don't want indexes, you want zip. Commented Jul 2, 2013 at 14:04

4 Answers 4

14
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 | 
Sign up to request clarification or add additional context in comments.

Comments

2
for u in user: print '|',u,'|',info[user.index(u)][0],'|',info[user.index(u)][1],'|',info[user.index(u)][2],'| \n' 

Comments

1
>>> g = 0 >>> for u in user: ... print '|',u,'|',info[g][0],'|',info[g][1],'|',info[g][2],'| \n' ... g=g+1 ... | X | a | b | c | | Y | d | e | f | | Z | g | h | i | 

Comments

0

The following code works too:

>>> for i in zip(user,info): print i[0],'|', for x in i[1]: print x,'|', print 

And I get the output:

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

P.S.:I know there have been a couple of answers, But I just thought this is also a way to get the result and thats why I have added it!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.