A
A
anya_hacker2021-07-10 09:57:01
Python
anya_hacker, 2021-07-10 09:57:01

Why IndexError when populating an array?

There is a matrix (list of lists).
It is necessary to change the numbers on the main diagonal: if the number is less than zero, then replace it with 0, otherwise with one.
Example:
Input:

[
  [-1,  4, -5, -9,  3 ],
  [ 6, -4, -7,  4, -5 ],
  [ 3,  5,  0, -9, -1 ],
  [ 1,  5, -7, -8, -9 ],
  [-3,  2,  1, -5,  6 ]
]


Conclusion:
[
  [ 0,  4, -5, -9,  3 ],
  [ 6,  0, -7,  4, -5 ],
  [ 3,  5,  1, -9, -1 ],
  [ 1,  5, -7,  0, -9 ],
  [-3,  2,  1, -5,  1 ]
]

The main diagonal - from the upper left corner to the lower right
I wrote a program where a new matrix with numbers is created.
But when accessing the index of the list (it is initially empty), an exception is thrown.
Why writes indexerror?
The code:
def res(m):
    matrix = [[] for _ in range(len(m))] # новая пустая матрица
    for i in range(len(m)):
        for j in range(len(m[i])):
            if i == j and m[i][j] < 0: # i - индекс списка в матрице, j - индекс элем. в конкретном сп.
                matrix[i][j] = 0 # новый элемент, равный нулю. Здесь и вылетает исключение
            elif i == j and m[i][j] >= 0:
                matrix[i][j] = 1
            else:
                matrix[i][j] = m[i][j]
    return matrix


print(res([
    [-1, 4, -5, -9, 3],
    [6, -4, -7, 4, -5],
    [3, 5, 0, -9, -1],
    [1, 5, -7, -8, -9],
    [-3, 2, 1, -5, 6]
]))


Exception:
matrix[i][j] = 0
IndexError: list assignment index out of range

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2021-07-10
@anya_hacker

This is not done in python, to add an element to a list, use the .append() method

if i == j and m[i][j] < 0: # i - индекс списка в матрице, j - индекс элем. в конкретном сп.
    matrix[i].append(0)
elif i == j and m[i][j] >= 0:
    matrix[i].append(1)
else:
    matrix[i].append(m[i][j])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question