Output is correct (no error produced) but upon submission I'm getting an error?

Screen Link: https://app.dataquest.io/m/352/object-oriented-python/9/creating-an-append-method

My Code:

class MyList:

    def __init__(self, initial_data):
        self.data = initial_data
        
    # Add method here
    def append(self, new_item):
        self.data += new_item

my_list = MyList([1,2,3,4,5])
print(my_list.data)

my_list.append([6])
print(my_list.data)

What I expected to happen:
I expected to be able to pass a list in as an argument instead of using the function to convert the argument into a list.

What actually happened:

The output is correct when I run the code, no errors and I see [1,2,3,4,5,6]
But when I Submit Answer, I get this error:

"Calling method  `append`  from class  `MyList`  with arguments  `new_item=6`  caused an error:  `TypeError: 'int' object is not iterable` ."

Why the error upon submitting the answer but not when I actually run the code? If I put this code into Jupyter it also runs without any errors. What’s up with this? Why can’t I just pass a list in as the argument instead of saying the new_item is a list within the method?

2 Likes

Because they are testing your code with the value 6 and not with the list [6]. The error occurs because when the value to be appended is 6 your method can’t handle that as you can’t use + operator for a list and an integer datatype.

The instructions are to append values to the list. Your class method needs to handle the conversion of 6 to [6] instead of trying to append a list to the existing list.

4 Likes

For those who are still wrapping the head around.

You don’t have the sent the list [6] as an argument. The instruction is to use the append() method to append value 6 to my_list .

So we need to send the value as an argument then convert them into list using simple method of “value = [value]”

Hope that helps. Happy learning