Search code examples
pythonxbmc

python error: IndexError: list index out of range


I need some basic help with my code, I'm trying to create a new list with the value for the variable self.add_programs in each time when I use the variable program_controls to add a list of buttons to store in the arrays.

When I try this:

self.add_programs = list()
self.rows += 1

program_controls = xbmcgui.ControlButton(
    int(position_start), 
    int(position_top), 
    int(program_width), 
    int(program_height), 
    program_title, 
    focusTexture = self.path + self.button_focus, 
    noFocusTexture = self.path + self.button_nofocus,
    textColor ='0xFFFFFFFF',
    focusedColor ='0xFF000000'
)
self.add_programs[self.rows].append(ProgramControls(program_controls, program))

It give me the error: IndexError: list index out of range

The error are jumping on this line:

self.add_programs[self.rows].append(ProgramControls(program_controls, program))

Here is the code:

class ProgramControls(object):
     def __init__(self, control, program):
         self.control = control
         self.program = program



class MyClass(xbmcgui.WindowXML):

    def __init__(self):
        self.add_programs = list()
        self.rows = 0

    def GoDown(self):
        self.add_programs = list()
        self.rows += 1

        program_controls = xbmcgui.ControlButton(
            int(position_start), 
            int(position_top), 
            int(program_width), 
            int(program_height), 
            program_title, 
            focusTexture = self.path + self.button_focus, 
            noFocusTexture = self.path + self.button_nofocus,
            textColor ='0xFFFFFFFF',
            focusedColor ='0xFF000000'
        )
        self.add_programs[self.rows].append(ProgramControls(program_controls, program))
    prog_button = [elem.control for elem in self.add_programs]


    if self.programs == False:
       self.addControls(prog_button)

Can you please help me how I can store the buttons in the arrays in each time when I add a list of buttons?

If that is possible, please let me know.


Solution

  • If you do mylist[3].append() you're trying to append to a list that's the 4th item in your mylist. You could also write this as (mylist[3]).append() to make this more clear.

    If you want to append to mylist, you need to just use mylist.append(). If you want to set it on a certain index, you can use list.insert(index, item); however, if the list is not as long as index, it'll just be appended at the end.

    If you want to use specific keys, use a dict() instead:

    mydict = {}
    dict[3] = my_item
    

    In your case, I'd just use self.add_programs.append() however.