Home > Back-end >  Index from list doesn't work: IndexError: invalid index to scalar variable
Index from list doesn't work: IndexError: invalid index to scalar variable

Time:10-14

I have a problem with the index of a list.

I will explain my code for you.

lijst1 and lijst2 are lists with coordinates. I want to separate de x and y from the coordinates. So i use index 0 for x-coordinates and index 1 for y-coordinates. If I print 'lijst1x', I print all the x-coordinates If I print for example 'lijst1x[5]' it gives an error: Traceback (most recent call last): File "C:\Users\tmdek\viktor-demo\Experiment\app.py", line 137, in print(lijst1x[5]) IndexError: invalid index to scalar variable.

I want to calculate 'stapx' and 'stapy' but the answer is not correct because there is something wrong with lijst1x, lijst2x, lijst1y and lijst2y. How can i solve this problem?

for index in range(len(lijst1)):
    lijst1x = lijst1[index][0]
    lijst2x = lijst2[index][0]
    lijst1y = lijst1[index][1]
    lijst2y = lijst2[index][1]


    stapx = (lijst1x-lijst2x) / (aantal_punten_tussen_coordinaten   1)

    stapy = (lijst1y - lijst2y) / (aantal_punten_tussen_coordinaten   1)

CodePudding user response:

lijst1 and lijst2 are lists, so indexing to a value works, lijst1x is a variable made inside the loop, it is a scalar value which is overwritten every iteration. Thats why indexing to a value on a scalar variable gives the error.

maybe declare empty list lijst1x first, then try the following

lijst1x = lijst1x.append(lijst1[index][0])

do the same for all.

CodePudding user response:

@murari

lijst1x = []
for index in range(len(lijst1)):
    lijst1x = lijst1x.append(lijst1[index][0])
    print(lijst1x)

Now I got the next error: Traceback (most recent call last): File "C:\Users\tmdek\viktor-demo\Experiment\app.py", line 133, in lijst1x = lijst1x.append(lijst1[index][0]) AttributeError: 'NoneType' object has no attribute 'append'

  • Related