Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading