Python Object-Oriented Python Inheritance Instances

Son-Hai Nguyen
Son-Hai Nguyen
1,667 Points

I need help on this ```combiner()``` exercise

Please have a look at my following method. I tested it on Worksplaces, it worked just fine just like the requirement, but somehow the Recheck work kept saying there's a TypeError: sequence item 0: expected str instance, list found Is there anyone know what I missed?

Thank you!!!

instances.py
def combiner(*args):
    numLs = []
    strLs = []
    for a in args:
        if isinstance(a, (int, float)):
            numLs.append(a)
        else:
            strLs.append(a)
    sumInt = str(sum(numLs))
    strLs.append(sumInt)
    return ''.join(strLs)

combiner("apple", 5.2, "dog", 8)          

3 Answers

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 51,914 Points

*args accepts a variable list of arguments (so there can be more than one). The challenge will pass in a single list (any number of items but they will be enclosed in brackets so there will only be one list)

The easiest fix to your code is just remove the * from your parameter

Son-Hai Nguyen
Son-Hai Nguyen
1,667 Points

Great!!! It sounds weird to pass all variables in as a single list anw

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 51,914 Points

The function takes a single argument. If you want to test in a workspace try:

print(combiner(["apple", 5.2, "dog", 8]))
Son-Hai Nguyen
Son-Hai Nguyen
1,667 Points

Thanks Kris, for your answer. But what does it mean? Doesnt the *args stand for a list of arguments? How to iterate through it (since it's still a list right? I saw the [] here) if it's a single argument?

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 51,914 Points

If you add print statements you better see what is going on:

def combiner(*args):
    numLs = []
    strLs = []

    for a in args:
        print(a)

        if isinstance(a, (int, float)):
            numLs.append(a)
        else:
            strLs.append(a)
    sumInt = str(sum(numLs))
    strLs.append(sumInt)

    print(strLs)

    return ''.join(strLs)

print(combiner(["apple", 5.2, "dog", 8]))

In the loop a is a list so since it since it isn't an int or float it is appended to strLs. Since that is the only argument there are no numbers to sum so sumInt = '0'. Append this to strLs you end up with [['apple', 5.2, 'dog', 8], '0']. At which point using join on a list and a string causes the error.