Referencing arguments given

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

My Code:

    class NewList(DQ):
        """
        A Python list with some extras!
        """
        def __init__(self, initial_state):
            self.data = initial_state
            
        def append(self, new_item):
            self.data = self.data + [new_item]
            
    my_list = NewList([1, 2, 3, 4, 5])
    print(my_list.data)
    my_list.append(6)
    print(my_list.data)

What I expected to happen:

My question is - why do I need to reference the given argument in brackets [new_item]?

What actually happened:

Replace this line with the output/error

Hi @hunter.kiely: Recall that lists can only be concatenated with lists. Thus you need to use square brackets [ ] as shown.

How do I know that new_item is going to take a list rather than a string?

Hi @hunter.kiely: In this case the objective is to append the integer 6 to my_list. All the elements in the existing my_list are of type int. Thus you will need to add the new_item to the list but in this case python does not allow concatenation of list and int. Thus you need to implicitly convert new_item to a list by using the square brackets.

If the types of the elements in my_list was all originally string then new_item should also be type string. Note that:

Explicit conversion using the list() method in this case will not work for integers and will throw an error.

class NewList(DQ):
        """
        A Python list with some extras!
        """
        def __init__(self, initial_state):
            self.data = initial_state
            
        def append(self, new_item):
            self.data = self.data + list(new_item)
            
my_list = NewList([1,2, 3, 4,5])
print(my_list.data)
my_list.append(6)
print(my_list.data)

while this will work for strings

class NewList(DQ):
        """
        A Python list with some extras!
        """
        def __init__(self, initial_state):
            self.data = initial_state
            
        def append(self, new_item):
            self.data = self.data + list(new_item)
            
my_list = NewList(['1','2','3','4','5'])
print(my_list.data)
my_list.append('6')
print(my_list.data)

Since explicit list conversion is only allowed for type string and not type int.

Hope this clarifies!

2 Likes