3

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.

user4046073
  • 821
  • 4
  • 18
  • 39

3 Answers3

3

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)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

For that you'll need to append a list to a list first, i.e.:

list = []
list.append([])
list[0].append(0)
print(list)
# [[0]]
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
0
lst = []
lst.append([0,1])
lst.append([2,3])
lst.append([0,4])
print(lst)

How about this ? Or you need in the form of loop with constant set of numbers?

sanyassh
  • 8,100
  • 13
  • 36
  • 70
Nasrath D
  • 11
  • 2