0

I am trying to define a list of lists with a loop in Python. I want to construct the following list:

x=[[0,0],[1,0],[2,0],...,[9,0]]

Here is basically what I do:

x=[[0,0]]*10
for i in range(10):
    x[i][0]=i
print x

However, I end up with the following list:

x=[[9,0],[9,0],[9,0],...,[9,0]]

What am I doing wrong? Thank you so much for your help

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Doon_Bogan
  • 359
  • 5
  • 17

3 Answers3

1

Is this what you are trying to do?

>>> [[i, 0] for i in range(10)]
[[0, 0], [1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]]

What was wrong with that you were doing is that you were creating a list, and then by using the * you were not creating more, you were just making more references to it, this means that each time you changed the list, you were changing the same list each time.

>>> a = [[]]*10
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a[0].append('X')
>>> a
[['X'], ['X'], ['X'], ['X'], ['X'], ['X'], ['X'], ['X'], ['X'], ['X']]
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
1

When you do

x=[[0,0]]*10

you are not creating 10 different elements, but simply copying the reference to the same element 10 times. What you actually need is

x=[[i,0] for i in range(10)]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

use this,

a=[[0,i] for i in range(10)]
print a

output is like:

[[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9]]
Ashif Abdulrahman
  • 2,077
  • 1
  • 10
  • 4