2

I have a list of size 1000, data_0. And, I wanted to refer to an element located at index 250. So, for this, I tried to run following line of code:

data_0[len_0/4]

Here, len is an integer with value "1000". Even with this simple statement, the python intepretor throws following error:

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

At other places, I got following error for a similar symptomn: TypeError: slice indices must be integers or None or have an __index__ method

3
  • 1
    Try data_0[int(len_0/4)] Commented Dec 18, 2021 at 10:18
  • 5
    division / will return float, e.g. 250.0. Use floor division 1000//4 Commented Dec 18, 2021 at 10:18
  • 1
    Does this answer your question? Why does integer division yield a float instead of another integer? Commented Dec 18, 2021 at 10:19

1 Answer 1

1

Python division returns a value of type float, even if it is a division with no remainder. Index the data as data_0[int(len_0/4)] to retrieve the item at index 250. Keep in mind, if you are accessing 250 it may be in reality at index 249 since lists are started at 0, and the index may need to be subtracted by one. Subtraction between two integers will return an integer!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.