Python Forum

Full Version: apendng to a list within a class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i am trying to understand classes how to create list within them and how to append to that list.
i guess i missed a basic understanding of appending somewhere. or something else.
but for instance i try to append to a list like this.
when i run this and enter "grape" to be the appended item , nothing gets returned..

class Fruit:
    fruit_list = []
    def __init__(self,name):
        self.name = name

    def named(self):
        print("{} is a fruit".format(self.name))

    def append1(self):
        inp = input("add a fruit: ") 
        if input == " ":
            self.fruit_list.append(inp)
            return
        self.fruit_list
        

apple = Fruit('apple')
apple.append1() 
Your input() method asks for a fruit (line 10).

On line 11, you're comparing the input function against a single space. This will never be true, so execution goes to line 14 and the method exits without doing anything.

I assume you meant to compare it to inp instead of input. If you did that and the fruit you entered was a single space, it would add that space it to the list (lines 11-12).
If it were any other string, nothing is done and fruit_list remains the same.

Even if you had modified the list, nothing in this script will show the contents. You'd need to print the attribute (or do something with it) to see the results.
So like this?
class Fruit:
	fruit_l=[]
	def __init__(self,name):
		self.name=name
		
	def named(self):
		print('{} is a fruit'.format(self.name))
		
	def list1(self):
		inp = input('enter a fruit: ')
		if inp:
			self.fruit_l.append(inp)
			print(self.fruit_l)

apple = Fruit('apple')
apple.list1()
That looks more functional. I'm not sure why a "Fruit" object should have another list of fruits, or how it relates to itself, but that code should append to the list and display it.
Couple of observations:
1. It does not make sense for a Fruit class to have a list to add more fruits. Fruit class should be one kind of fruit. You can have a list, outside the class to collect different Fruit instances.
2. fruit_l is class attribute (not an instance attribute) and mutable, it will be shared among all instances of Fruit class, so prepare for a surprise/gotcha experience.