Home > Software design >  M[i,j]=randint(2,99): TypeError: list indices must be integers or slices, not tuple
M[i,j]=randint(2,99): TypeError: list indices must be integers or slices, not tuple

Time:10-12

from numpy import *
from random import *
M=([[int]*20]*20)
def saisie():
    N=int(input("Saisir l'ordre de la matrice "))
    while not 4<N<20:
         N=int(input("Saisir l'ordre de la matrice "))
    return(N)
N=saisie()
def matrice(N):
    for i in range(N):
        for j in range(N):
            M[i,j]=randint(2,99)
    return(M)
x=matrice(N)

I'm getting (M[i,j]=randint(2,99): TypeError: list indices must be integers or slices, not tuple ) however the list indices are integers, what did i do wrong?

CodePudding user response:

You should assign it to a list of lists like this.

M[i][j] = randint(2,99)

CodePudding user response:

For numpy arrays this might work, M is just a standard python list, that does not allow multi indexing.

M[i][j]= randint(2,99) should work

Better use M = np.random.randint(2,99, size=(20,20)) just one line of code and no need for loops.

CodePudding user response:

You should use it like this:

M[i][j]=randint(2,99)

CodePudding user response:

There's a couple things here. One you can use numpy for this:

np.random.randint(2,99, size=(20,20))

Regardless, the way you initialize M is going to come back to haunt you. M=([[int]*20]*20). Let me give you an example:

In [32]: M=([[0]*5]*5)

In [33]: M
Out[33]:
[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

In [34]: M[0][0] = 5

In [35]: M
Out[35]:
[[5, 0, 0, 0, 0],
 [5, 0, 0, 0, 0],
 [5, 0, 0, 0, 0],
 [5, 0, 0, 0, 0],
 [5, 0, 0, 0, 0]]

Notice that when you do that syntax and try to change a single element, you're actually changing all the elements across the column. Why? Because that outer * is copying the pointer of the list. Instead you can use list comprehension for this.

In [44]: M=[[0]*5 for _ in range(5)]

In [45]: M
Out[45]:
[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

In [46]: M[0][0] = 5

In [47]: M
Out[47]:
[[5, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

Notice that I'm not using the outer * and now when I change a single element within the list of lists, only one element is changed.

  • Related