0

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()
Hina Satti
  • 55
  • 6
  • Possible duplicate of [Create an empty list in python with certain size](https://stackoverflow.com/questions/10712002/create-an-empty-list-in-python-with-certain-size) – Craig May 22 '19 at 02:37
  • In `__init__`, you can initialize the list using `self.size = ['free'] * 10`. Lists in python are dynamic, so initializing this way is the same as what your code is trying to do. – Craig May 22 '19 at 02:39
  • 3
    This sounds like an [xy problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). You rarely need to do this with python. Why do you need this — maybe there's a more Pythonic way? – Mark May 22 '19 at 02:40
  • I too think this is an XY problem. You should rely on methods to dynamically add (e.g. `.append` or `.extend`) to your list as you need it. Rarely should you initialize a list with "empty" values. Or, are you coming from a language like javascript, where indexing into an array out of bounds gives you some null-like value (e.g. `undefined`). EDIT: re-reading, if you are coming from Java, you should use this like `List` interface, not like primitive arrays, where you declare some fixed size. Python does not generally work this way, learn to do it the Python way to make writing Python easier – juanpa.arrivillaga May 22 '19 at 02:49
  • @MarkMeyer I am trying to create a class which stores a 'type' and list/array which stores numbers for multiple entries. For example type = maths, size = [marks of different students] so this class should store marks for all students. – Hina Satti May 22 '19 at 02:51
  • 2
    @HinaSatti just `.append` to the list, you don't need to worry about the size of the list. A list is not like a primitive array – juanpa.arrivillaga May 22 '19 at 02:52

3 Answers3

0

This code won't work because size[i] does not exist. Instead use size.append(...). Also you should pass a number to makespace so that you can make space for an arbitrary number of items.

class Levels:

    def __init__(self, kind='A', size=10):
        self.kind = kind
        self.size = [ 0 for _ in range(10) ]

These slight changes make your code more robust and more pythonic.

First but the least important is that type is a builtin-method (also a class and also a type) so kind is often substituted.

Second You can pass default arguments to the constructor (or any function) as you should generally avoid having constants inside functions like that. Here you can arbitrarily set a Level's kind, as well as the initial space required.

Third Using list-comprehension you can create a list of arbitrary size (or elements). The syntax is

[ expression for args in iterable ]

which allows for any expression to be generated based on arguments passed from an iterable. Read more about list comprehension and other datastructure here.

As for your makespace you shouldnt really need it, however you could change the implementation so you can allocate more space (using self.size.append(...)) or overwriting currently used space.

Best of luck!

Community
  • 1
  • 1
Ranga
  • 620
  • 1
  • 7
  • 9
0

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!

babaliaris
  • 663
  • 8
  • 16
-1

If you want to have 10 free spaces in the list upon initializing, change

self.size = [] 

to

self.size = [“free”] * 10

If you want to start with an empty list and add 10 free spaces in your makespace loop, simply use

self.size.append(“free”)

Also, you really don’t need to pass size to makespace. Since you’re already passing self, I would just reference self.size from inside the makespace function.

Daniel C Jacobs
  • 691
  • 8
  • 18