Home > Enterprise >  Adding values to an empty 2D list (TypeError)
Adding values to an empty 2D list (TypeError)

Time:02-25

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)]

CodePudding user response:

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

CodePudding user response:

You have many mistakes in this code.

The values_to_go list is not a 2d list. The (7) or any number between parentheses is totally equal to a number without any parentheses. If you want to make it a tuple, you should tell python that these are not parentheses around the number; but these are tuple signs. So 7 is totally equal to (7). You should use (7,) to tell python that this is a tuple with one member which is 7. So this ... = values_to_go[i][0] will be OK.

Another mistake is the part that you've written to append members into the empty list. You cannot point to a non-existent member of a list with this expression: list[i][0]. There is no list[i] and therefore obviously there is no list[i][0]. If you want to append into the end of the list, you should just do it:

list.append(anything)

This would be something like this:

>>> values_to_go = [(7,), (8,), (9,)]  # or [[7], [8], [9]]
>>> some_list = []
>>> for i in range(len(values_to_go)):
...     some_list.append(values_to_go[i][0])
...
>>> print(some_list)
[7, 8, 9]

>>> # and if you want to make it 2D:
>>> some_list = []
>>> for i in range(len(values_to_go)):
...     some_list.append([values_to_go[i][0]])
...
>>> print(some_list)
[[7], [8], [9]]
  • Related