Mozammil Khan
Mozammil Khan

Reputation: 21

Keep getting a ValueError: not enough values to unpack (expected 2, got 1)

My assignment:

Write a short Python function, minmax(data), that takes a sequence of one or more numbers, and returns the smallest and largest numbers, in the form of a tuple of length two. Do not use the built-in functions min or max in implementing your solution.

Here's the code:

def minmax():
    data = input("Enter a list of any input > ")
    max, min = data[0]
    for x in data:
        if x > max:
            max = x
        elif x < min:
            min = x
    print (max, min)
minmax()

This gives me ValueError: not enough values to unpack (expected 2, got 1). How do I fix this?

Upvotes: 2

Views: 12307

Answers (4)

ANK
ANK

Reputation: 595

There are bugs in your code:

  1. You should define your list format. Such as input numbers are separated by ",","" etc.
  2. when you assign data[0] to min and max, you have to put = between min and max.

Please make changes in your code as shown below:

data =[int(x) for x in input().split(",")]
max = min = data[0]

Please provide the input list as number1, number2, number3 etc.

This will work correctly.

Upvotes: 1

Shivam Pandya
Shivam Pandya

Reputation: 261

You have not converted the input into a list, and you have defined min and max in a wrong way.

Do this to convert inputs into list:

data.split(" ") #if every number is separated by space

And for min and max, you're assigning two value by saying

min, max= data[0]

do it like this:

min=max=data[0]

You can cheat on this program in a way, if only condition is not using min and max function. You're sorting the list in a manner. However you can also do this:

def minmax():
    data = input("Enter a list of any input > ")
    myList= data.split(" ")
    myList.sort()
    print(myList[0], "is minimum and", myList[-1],"is max")
minmax()

Upvotes: 0

Bishwas Mishra
Bishwas Mishra

Reputation: 1343

data is a tuple that holds your input items in the form (1, 2). You are doing data[0] which means you are getting the first item from data tuple, which is just one item, not two. Then with the command max, min = data[0] you are telling python to extract two items from one item data[0].

Instead use:

max, min = data

Upvotes: 0

Prune
Prune

Reputation: 77837

You've used the wrong syntax. I believe that what you're trying to do is to initialize both min and max to the first element of the list. The assignment you used is for multiple assignment -- with two variables on the left, you must have two values on the right.

However you want the user to enter the input is fine; simply split the input on the delimiter you choose, and then use that for split.

Also, remember to convert the values from string to int (left as an exercise for the student).

The important syntax for the error you gave is

min = max = data[0]

Now you can continue with your loop.

Upvotes: 3

Related Questions