Reworking loop in Python

Question:

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.

Asked By: Chris Steele

||

Answers:

for s in status:
    if(s == -1):

This will look better for sure, and may be slightly more efficient.

Answered By: Grzegorz Szymala

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) 
Answered By: Nuno André
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.