Reworking loop in Python

I have a Python loop that looks like this:

for i in range(n):
   if (status[i]==-1):
      <main code>

I’m sure there is a better way to do this – some kind of "where" in the iterator?

The code runs as expected, it is just inefficient and slow. If I have 200000 records and only 30 of them have a status[i]==-1, I don’t want to examine all 200000.

>Solution :

Iterating a Python list is inherently slow. Try some vectorization library as numpy, which is implemented in C and can perform operations like this several hundred times faster. E.g.

import numpy as np

arr = np.array(status)
x = np.where(arr == -1)

print(x) 

Leave a Reply