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.

2
  • 2
    "Is it not appending 0 to the first item in the list?" What first item in the list? That list is empty. Commented Apr 3, 2019 at 9:51
  • 1
    I must notice that shadowing built-in name list with list = [] is not a good idea. Commented Apr 3, 2019 at 11:18

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. But if it is in a loop, how do I initialise the n item before append?
@user4046073 Edited mine,
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]]

Comments

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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.