'Adding values to an empty 2D list (TypeError)
I'm trying to add values to an empty 2d list with this code:
values_to_go = [(7, 6, 2, 2, 350.0, '6', '11/05/2022\n', 7), (8, 6, 2, 1, 350.0, '08:30-10:30\n', '15/06/2022\n', 7), (9, 6, 2, 1, 350.0, '16:00-18:00\n', '25/08/2022\n', 7)]
list = []
for i in range(len(values_to_go)):
list[i][0] = values_to_go[i][0]
list[i][1] = values_to_go[i][5]
list[i][2] = values_to_go[i][6]
list[i][3] = values_to_go[i][2]
print(list)
But I'm getting this error:
TypeError: 'int' object is not subscriptable
Expected output: values_to_go = [(7, 6, 11/05/2022\n, 2), (8, 08:30-10:30\n, 15/06/2022\n, 2), (9, 16:00-18:00\n, 25/08/2022\n, 2)]
Solution 1:[1]
When you create your list, it is empty, so basically you can't access any position of it, first you have to create them you can do this with the .append() function.
Your code could look like this:
mylist = [[],[],[]]
for i in range(len(values_to_go)):
mylist[i].append(values_to_go[i][0])
mylist[i].append(values_to_go[i][5])
mylist[i].append(values_to_go[i][6])
mylist[i].append(values_to_go[i][2])
output: [[7, '6', '11/05/2022\n', 2], [8, '08:30-10:30\n', '15/06/2022\n', 2], [9, '16:00-18:00\n', '25/08/2022\n', 2], ]
Some extra tip, list is a Python reserved word, so don't use it as a variable name
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 |
