I am trying to create a list within a class and then declaring elements in that list. I don’t even know if this is the right way for python. I have some java background.
I didn’t add 10 elements in the list manually because I feel creating a dynamic list will be more useful.
class Levels: def __init__(self): self.type = "A" self.size = [] # trying to create a list for 10 elements. self.makespace(self.size) # running this method to create 10 spaces and then declare them. def makespace(self, size): for i in range(0,10): if(size[i] == None): size[i] = "free" print(i) else: print("Didn't work") print(i) test = Levels()
Advertisement
Answer
Your problem lies in here.
if(size[i] == None): size[i] = "free" print(i)
At this moment, size is empty, it doesn’t contain any elements so why are you
checking size[i] == None
?
You probably think that a python list behaves like an array in Java where it initializes everything with null? Even though here you are not declaring the size of the list inside the init constructor, so I’m curious how you thought of that.
Your code should look like this:
class Levels: def __init__(self): self.type = "A" self.size = [] # trying to create a list for 10 elements. self.makespace(self.size) # running this method to create 10 spaces and then declare them. def makespace(self, size): #This will fill the emty list with 10 None(null) values for i in range(0,10): size.append(None) test = Levels()
Also a bonus:
class Levels: def __init__(self): self.type = "A" self.size = [] #Notice that I'm not passing self as an argument when I call makespace() self.makespace() def makespace(self): #This will fill the emty list with 10 None(null) values for i in range(0,10): self.size.append(None) test = Levels()
Self is the this keyword in python, the difference is that in Python you need to pass it as an argument only when declaring methods, not when you call them and also you can name it whatever you want!
Hope this helps!