close

How to fix Index: invalid index to scalar variable

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to fix Index: invalid index to scalar variable in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to fix Index: invalid index to scalar variable?

  1. How to fix Index: invalid index to scalar variable?

    You are trying to index into a scalar (non-iterable) value:
    [y[1] for y in y_test] # ^ this is the problem

  2. fix Index: invalid index to scalar variable

    You are trying to index into a scalar (non-iterable) value:
    [y[1] for y in y_test] # ^ this is the problem

Method 1

You are trying to index into a scalar (non-iterable) value:

[y[1] for y in y_test]
#  ^ this is the problem

When you call [y for y in test] you are iterating over the values already, so you get a single value in y.

Your code is the same as trying to do the following:

y_test = [1, 2, 3]
y = y_test[0] # y = 1
print(y[0]) # this line will fail

I’m not sure what you’re trying to get into your results array, but you need to get rid of [y[1] for y in y_test].

If you want to append each y in y_test to results, you’ll need to expand your list comprehension out further to something like this:

[results.append(..., y) for y in y_test]

Or just use a for loop:

for y in y_test:
    results.append(..., y)

Method 2

Basically, 1 is not a valid index of y. If the visitor is comming from his own code he should check if his y contains the index which he tries to access (in this case the index is 1).

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read