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
  • 767
  • 2
  • 15
  • 31

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)
U12-Forward
  • 65,118
  • 12
  • 70
  • 89
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
  • 85,689
  • 29
  • 230
  • 253
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
  • 7,382
  • 12
  • 27
  • 61
Nasrath D
  • 1
  • 1