Issue
I am working on a project that requires dynamically creating and populating nested arrays in Python. But there is an error, and I can't find the issue in my code.
def pop_array(rows, cols):
ar = [[]]
for i in range(rows):
for j in range(cols):
ar[i][j] = i + j
return ar
rows = 3
cols = 4
result = pop_array(rows, cols)
print(result)
I want to create a 2D array with the specified number of rows and columns and populate it with some values. However, the code is giving me an out of range error:
IndexError: list index out of range
Thanks for your time
Solution
When you write ar = [[]], you create a list containing one empty list.
So, when you later try to access ar[i][j], you encounter an IndexError because ar[i] is an empty list, and you can't access an element at index j within an empty list.
Try this:
def pop_array(rows, cols):
ar = [[0] * cols for _ in range(rows)]
for i in range(rows):
for j in range(cols):
ar[i][j] = i + j
return ar
rows = 3
cols = 4
result = pop_array(rows, cols)
print(result)
Answered By - TheHungryCub
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.