Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Dean Shalem
Dean Shalem
3,089 Points

my instances.py task 1 of 1, works in workspace but I keep getting error

My code works in the workspace, definitely returns what they asked for, why won't treehouse accept my submission?

output: Bummer: TypeError: sequence item 0: expected str instance, int found.

I also tried covering my return statement with str( my_return_statement ), still will not accept my submission. hmmmmm any answers why?

The assignment statement: "Alright, here's a fun task! Create a function named combiner that takes a single argument, which will be a list made up of strings and numbers. Return a single string that is a combination of all of the strings in the list and then the sum of all of the numbers. For example, with the input ["apple", 5.2, "dog", 8], combiner would return "appledog13.2". Be sure to use isinstance to solve this as I might try to trick you."

instances.py
def combiner(l):
    c = 0
    for i in l:
        if isinstance(i, (int, float)):
            c+=i
            l.remove(i)
    return ("".join(l) + str(c))

1 Answer

Jimmy Sweeney
Jimmy Sweeney
5,649 Points

Dang that's clever... however it won't work with any list. Your solution will only work if the list alternates between strings and ints/floats. Someone smarter than me will probably be able to describe this better, but basically this is what I think is going on:

Each time that you remove an item from the list, you end up skipping something. For example if your list was just numbers like so: [1, 2, 3, 4, 5]. Then your for-loop will skip essentially skip an item in the loop.

First time through the loop: c = 1 list = [2, 3, 4, 5] (I renamed your variable "l" to "list" because it's easier to read)

Second time through the loop: c = 4 list = [2, 4, 5]

Whoa, why did it proceed to the 3rd element in the list? Because now the second element in the list [2, 3, 4, 5] is 3. In other words list[1] == 3.

c is equal to 4 because it added 1 + 3.

Now the third time through the for loop, the program will look for the third element in the list [2, 4, 5] which is 5.

Hopefully that makes sense. As far as I understand, you probably don't want to use .remove in a for-loop.