0

My code is as follows:

l = [[]] * 10
for i in range(10):
  l[i] += [0]

I need a 10 x 1 matrix of zeros.

It doesn't work as expected because the list comprises references to the same variable. As a result, I am getting a 10 x 10 matrix.

How to prevent it?

Andrey
  • 5,932
  • 3
  • 17
  • 35

2 Answers2

2

Try this:

l = [[] for _ in range(10)]

This will create 10 independent sublists. You can then modify any of them without affecting the others. (The use of _ for the loop variable is a common Python convention for an unused loop variable.)

Here's an example of how modifying one sublist leaves the others unaffected:

>>> l[2].append(5)
>>> l
[[], [], [5], [], [], [], [], [], [], []]
>>> 
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
  • if we simply do `[[]]*10` that also accomplishes the same task right? would you like to add it to your answer?] – lifezbeautiful Sep 23 '21 at 09:47
  • @lifezbeautiful No, `[[]]*10` doesn't work, because it creates 10 references to the *same* list. This was pointed out in OP's post. You need the `[]` to be evaluated 10 times, resulting in the creation of 10 sublists, rather than just once. – Tom Karzes Sep 23 '21 at 10:35
0

There multiples ways to obtain what you are looking for :

There some possibilites

Using list comprehension

L = [[0] for k in range (10)]

Using numpy np.zeros function

L = np.zeros((10,1)).tolist() # if you want a list and not an array
Skaddd
  • 153
  • 8