简体   繁体   中英

Python - ValueError: Too many values to unpack

I have a very simple code where I want to loop through two lists at the same time. However, this gives me a ValueError: too many values to unpack.

def testing_something():
    list1 = [1,2,3,4,45]
    list2 = [1,4,4]
    return list1, list2

for q,z in testing_something():
    print (q,z)

The output of testing_something() is ([1, 2, 3, 4, 45], [1, 4, 4]), so I can imagine to be able to loop simultaneously through this output, with q in my case being [1, 2, 3, 4, 45] and z being [1,4,4]. Why does this raise a ValueError?

you can't use a single for to iterate over two lists at the same time. You should use zip function

def testing_something():
    list1 = [1,2,3,4,45]
    list2 = [1,4,4]
    return list1, list2

for q,z in zip(testing_something()):
    print(q)
    print(z)

Note that zip will iterate until the lists have elements: if it finishes iterating over one, it will stop iterating. This is solved with itertools.zip_longest , which would output None in correspondence of the out-of-bound index: should you want to use it, you have to import the itertools module

If you want q=[1, 2, 3, 4, 45] and z=[1,4,4] in the first (and only) iteration of the for loop, you should return [[list1, list2]] .

However, if you plan to only have one pair of lists returned, you can skip the for loop altogether (and keep the code you posted in the question):

q, z = testing_something()
print(q, z)

you can't iterate over single variable as your doing in your for loop,this is the easy way to q,z as your lists.

def testing_something():
    list1 = [1,2,3,4,45]
    list2 = [1,4,4]
    return list1, list2

q,z=testing_something()
print q
print z

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM