1

I am trying to create a list of lists

A = [[]]*4

printing A, gives

[[],[],[],[]]

Then I do the following

A[0].append(1)

the result comes out

[[1], [1], [1], [1]]

I want the following output:

[[1],[],[],[]]

Any advice to do so? And why the result is coming like this?

zephyr
  • 1,775
  • 6
  • 20
  • 31
  • have you tried this : `A[[0]] = 1` or `A[0][0] = 1` ? – angel Jun 13 '14 at 14:00
  • Any other way to achieve this ??? Like suppose i want an outer List with fixed size but want to grow inner lists e.g [[1,2,3],[0],[2,3],5]. Outer list is of size 4, but inner lists have variable size... – zephyr Jun 13 '14 at 14:04

2 Answers2

1

Using multiplication syntax results in creating 4 references to the same list. References are just another names for one and same list. That's why when you add something to one of them, and print results, you're printing references to the same list.

Maciej
  • 193
  • 2
  • 11
0
A = [[] for x in range(4)]

Now i can easily do

A[0].append(10)

Its gives desired output.

zephyr
  • 1,775
  • 6
  • 20
  • 31