'Why do I get "IndexError: list index out of range" when trying to add values to a nested list?
I'm trying to put some data to my nested list.
n_list = []
n = int(input())
for i in range(0, n):
name = input()
n_list[i].append(name)
val = int(input())
n_list[i].append(val)
print(n_list)
Solution 1:[1]
The problem is that you are trying to access the i-th item of an empty list. Since the list has 0 elements and you are asking for the i-th one, you get an error.
You could initialize a list with dummy values
n = int(input())
n_list = n * [None]
and then, write
n_list[i] = the_value
Solution 2:[2]
The mistake is pretty simple and expected, so nothing to feel bad about.
The append function works in the following way (syntax):
<list_name>.append(<item>)
is the name of the list and is the item to be inserted.
In your code,
n_list[i].append(name)
You are trying to append to the list present in i th index of n_list, which doesn't exist. So its showing the error
Solution 3:[3]
Like Andronicus said you dont need to use the index [i]. But you are talking about a 'nested list'. What you are trying to do is not 'nested'. Seems like you want to create a list of key/value objects:
n_list = []
n = int(input())
for i in range (0,n):
print(i)
name = input()
val = int(input())
n_list.append([name, val])
print(n_list)
Results in something like: [['myname', 2], ['yourname', 3]]
or as a dictionary:
n_list = []
n = int(input())
for i in range (0,n):
print(i)
name = input()
val = int(input())
n_list.append({'name': name, 'value': val})
print(n_list)
Results in something like: [{'name': 'myname', 'value': 3}, {'name': 'yourname', 'value': 4}]
Solution 4:[4]
This one is working. the reasons why your method didn't work it's because you were identifying an index that doesn't yet exist
n_list[i]
the list has no elements. that's why you need to append() the new ones.
n_list = []
n = int(input("write list length: \n"))
for i in range (n):
item = [] #create the nested list for each loop
name = input("Write name : \n")
item.append(name)
val = int(input("write value : \n"))
item.append(val)
n_list.append(item)
print(n_list)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | blue_note |
| Solution 2 | SHASHANKA SHEKHAR DAS 17BCE132 |
| Solution 3 | L3n95 |
| Solution 4 | Woobensky Pierre |
