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

  • 1
    Try `data_0[int(len_0/4)]` – kiner_shah Dec 18 '21 at 10:18
  • 5
    division `/` will return float, e.g. `250.0`. Use floor division `1000//4` – buran Dec 18 '21 at 10:18
  • 1
    Does this answer your question? [Why does integer division yield a float instead of another integer?](https://stackoverflow.com/questions/1282945/why-does-integer-division-yield-a-float-instead-of-another-integer) – buran Dec 18 '21 at 10:19

1 Answers1

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!

Keegan Murphy
  • 767
  • 3
  • 14