Anthony O'Brien
Anthony O'Brien

Reputation: 81

Why am I getting 'ValueError: too many values to unpack'?

So I have some python code -

list1 = ["Anthony", "Sean"] # define a table to use while testing

def IsInArray(val, *tab):   # define function to check
    for v, in tab:
        if v == val:
            return true
    return false

if IsInArray("Anthony", list1) == true:        # testing it
    print("Anthony is in list1")

if IsInArray("Charles", list1) == true:
    print("Charles is in list1")

but it says ValueError: too many values to unpack. I don't understand and the other threads are too different to understand how to fix this.

Upvotes: 1

Views: 371

Answers (4)

Daniel
Daniel

Reputation: 42748

Just use the in operator:

if "Anthony" in list1:        # testing it
    print("Anthony is in list1")

if "Charles" in list1:
    print("Charles is in list1")

Upvotes: 2

enedil
enedil

Reputation: 1645

You have extra comma that should be removed:

    for v, in tab:

After this - note that there is no such thing in Python as true or false - it's True and False.

I can spot new issue - even with all suggestions:

def IsInArray(val, *tab):   # define function to check
    for v in tab:
        if v == val:
            return True
    return False


IsInArray("Anthony", "Anthony", "Sean")
Out[6]: True

IsInArray("Anthony", ["Anthony", "Sean"])
Out[7]: False

In order to take a list as argument, remove asterix (*) in definition:

def IsInArray(val, tab):

Upvotes: 0

user2390182
user2390182

Reputation: 73450

Remove the comma and remove the * operator if you provide a list as second argument (and True, not true):

# def IsInArray(val, *tab):
def IsInArray(val, tab):   # define function to check
    for v in tab:
        if val in v:
            return True
    return False

Upvotes: 2

gdlmx
gdlmx

Reputation: 6789

You have 3 mistakes in the function (extra comma, True/False, and the conditional expression). Maybe this is what you mean to

def IsInArray(val, *tab):   # define function to check
    for v in tab:
        if val in v:
            return True
    return False

Upvotes: 1

Related Questions