smithdoto smithdoto - 5 months ago 11
Python Question

How can I initialize a list and append objects of any type to it in Python

I am trying to write a Python program that will initialize a list and add objects of any type to the list. I believe that I have initialized the list properly in my

__init__
method, but I cannot seem to pass any objects to it using the
.join()
method. I chose the
.join()
method because the
.append()
doesn't seem to handle object type
str
.

class Bag(object):
'''This is where the docstring goes.'''

def __init__(self):
self.contents = []

def put_in_bag(self, contents):
contents.join(contents)

def __str__(self):
return "The bag has: " + str(self.contents)

if __name__ == "__main__":
bag1 = Bag()
bag1.put_in_bag("comb")
bag1.put_in_bag("candy bar")
print bag1


I receive the following output:

The bag has: []


This is homework for a college course and I am an inexperienced Python programmer. It seems like it should be pretty straight forward, but I am obviously missing something.

Answer

You're not referencing the contents on the object instance (self) in the put_in_bag method; instead you're trying to join the argument to the argument itself and not touching the instance at all. Also, join is not a Python method on lists. Since you're adding single elements, you want append. If you want to add an entire list, use +=.

Try this:

class Bag(object):
    '''This is where the docstring goes.'''

    def __init__(self):
        self.contents = []

    def put_in_bag(self, contents):
        self.contents.append(contents)

    def __str__(self):
        return "The bag has: " + str(self.contents)

if __name__ == "__main__":
    bag1 = Bag()
    bag1.put_in_bag("comb")
    bag1.put_in_bag("candy bar")
    print(bag1)