Search code examples
pythonlistnested

python append to nested list , index out of range


I am trying to create a nested list. The result would be something like [[0,1],[2,3],[0,4]] I tried the following and got an index out of range error:

list = []
list[0].append(0)

Is it not appending 0 to the first item in the list? How should I do this? Many thanks for your help.


Solution

  • A little typo, you should do:

    list = [[]]
    list[0].append(0)
    

    You need to have a first element first...

    Edit:

    Use:

    list = []
    for i in range(3):
        list.append([])
        list[-1].append(0)