79172849

Date: 2024-11-09 13:21:02
Score: 1
Natty:
Report link

To elaborate on @luk2302's answer

In Python, when you say

temp_nums = [] or temp_nums = list(), you've created an empty list for the sole purpose of "growing" (appending) it later.

An array is a collection of data values in contiguous (next to each other) memory locations. Therefore, you can only index elements you have explicitly added to the collection.

Say,

temp_nums = list()

temp_nums[0] = 5 //This is going to fail

temp_nums.append(5) 
temp_nums[0] = 10   // This will now work since the array has "grown" in the previous step

If the number of elements you will be storing in the array is predetermined, then you can fill those elements with your custom default values so indexing will work.

temp_nums = [-1] * 5// This will create temp_nums = [-1, -1, -1, -1, -1]
temp__nums[0] = [9]  // This will be [9, -1, -1, -1, -1]

If the number of elements is dynamic, rewrite your code to follow the append() mechanism shown above.

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @luk2302's
  • Low reputation (1):
Posted by: chandanbsd