0

I have created a nested list l=[[-1]]*5 Now i want to append at position 2. How can I?

what happens

l = [[-1]]*5
>>> l
[[-1], [-1], [-1], [-1], [-1]]
>>> l[2].append(4)
>>> l
[[-1, 4], [-1, 4], [-1, 4], [-1, 4], [-1, 4]]

what I want is to append only at index2

>>> l
[[-1], [-1], [-1, 4], [-1], [-1]]
Amit
  • 11
  • 1
  • 2
  • `[[-1]]*5` gives you 5 references to the same inner list. To get 5 *different* inner lists, you can do `[[-1] for i in range(5)]`. This will create a new inner list for each outer list position. – Tom Karzes Aug 10 '19 at 07:42
  • `l = [[-1]]*5; index = 2; l[index] = l[index] + [-4]; print(l)` – Dravidian Aug 10 '19 at 07:58

1 Answers1

0

The issue is in a nessted list you can only realy call a section of the outer list and cant the inner if you extact the inner and add it then you can: x = [] For i in 1: x = x + 1[n] N = n + 1