jdayno22
jdayno22

Reputation: 1

"Too many values to unpack" when using a list

def singlelink(list1, list2):
    print(list1)
    print(list2)
    shortest = sys.float_info.max
    dist = 0.0
    for x1,y1 in list1:
        for x2,y2 in list2:
            dist = math.sqrt((float(x1)-float(x2))**2.0 + (float(y1)-float(y2))**2.0)  
            if dist < shortest:
                shortest = dist
    return shortest

I call the preceding function using the following

print(singlelink(['51.5217', '30.1140'], ['27.9698', '27.0568']))

When I do this, I get a ValueError: too many values to unpack (expected 2).

Each list only has two values, so unclear why it doesn't just unpack them into the variables

Upvotes: 0

Views: 165

Answers (4)

HTRS
HTRS

Reputation: 91

List or tuple unpacking in python works in the following way. For example, list1 contains two elements so you will unpack as a, b = list1. You can solve the question in following way instead of using loops.

def singlelink(list1, list2):
    print(list1)
    print(list2)
    shortest = sys.float_info.max
    dist = 0.0
    x1, y1 = list1
    x2, y2 = list2
    dist = math.sqrt((float(x1)-float(x2))**2.0 + (float(y1)-float(y2))**2.0)  
    if dist < shortest:
        shortest = dist
    return shortest

Upvotes: 2

Gabio
Gabio

Reputation: 9484

In order to unpack in the way you want, you don't need any loops, just provide the coordinates as tuples:

def singlelink(tup1, tup2):
    shortest = sys.float_info.max
    dist = 0.0
    x1,y1 = tup1
    x2,y2 = tup2
    dist = math.sqrt((float(x1)-float(x2))**2.0 + (float(y1)-float(y2))**2.0)  
    if dist < shortest:
        shortest = dist
    return shortest

print(singlelink(('51.5217', '30.1140'), ('27.9698', '27.0568')))

Upvotes: 0

pypalms
pypalms

Reputation: 461

This would be due to the way you are handling the lists:

for x1,y1 in list1:
        for x2,y2 in list2:

This is causing the issue, as you can only unpack a single item of a list at a time. I think what you may be trying to do is to send them as a list of tuples, which would be different logic.

x1,x2 = list1
y1,y2 = list2

You could also just access the elements of the list if you know they will only ever have an index < 2. I would only suggest this if you are always going to use lists, or want to expand this to longer lists.

dist = math.sqrt((float(list1[0])-float(list1[1]))**2.0 + (float(list2[0])-float(list2[1]))**2.0) 

Upvotes: 0

TQA
TQA

Reputation: 267

It's not possible to do that in a loop.

If there are only 2 elements in each list, you can unpack them in advance like this.

def singlelink(list1, list2):
    print(list1)
    print(list2)
    shortest = sys.float_info.max
    dist = 0.0
    x1, y1 = list1
    x2, y2 = list2
    dist = math.sqrt((float(x1)-float(x2))**2.0 + (float(y1)-float(y2))**2.0)  
    if dist < shortest:
        shortest = dist
    return shortest

Upvotes: 0

Related Questions