Sumail Brar
Sumail Brar

Reputation: 94

Index a list/array in python

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

Upvotes: 2

Views: 78

Answers (1)

Keegan Murphy
Keegan Murphy

Reputation: 832

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!

Upvotes: 1

Related Questions