np.extract(condition, arr) is functionally identical to indexing the array directly with that same boolean condition — both return a flattened 1D array of the elements where condition is True — but extract() takes the condition and array as two separate function arguments rather than using bracket-indexing syntax. It exists mostly for situations where a function-call style fits better, such as passing it as a callback, or when it slightly improves readability for a particular piece of code, but boolean indexing is the far more common and idiomatic way to express the same operation in everyday NumPy code.
1Understanding np.extract()
np.extract(condition, arr) is functionally identical to indexing the array directly with that same boolean condition — both return a flattened 1D array of the elements where condition is True — but extract() takes the condition and array as two separate function arguments rather than using bracket-indexing syntax. It exists mostly for situations where a function-call style fits better, such as passing it as a callback, or when it slightly improves readability for a particular piece of code, but boolean indexing is the far more common and idiomatic way to express the same operation in everyday NumPy code.
np.extract(condition, arr) and directly indexing the array with that same condition do exactly the same thing — boolean indexing is the far more common, idiomatic way to write it in everyday code, so reach for extract() mainly when its function-call form specifically fits your situation better.
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
print(np.extract(arr % 2 == 0, arr))2Practical Example
Here is a real-world application of np.extract() showing how it is used in production NumPy code.
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
print(np.extract(arr % 2 == 0, arr))
print(arr[arr % 2 == 0])3Best Practices
Follow these guidelines when working with np.extract():
1. Prefer boolean indexing over np.extract() in everyday code, since it's the more common, idiomatic NumPy style
2. Reach for np.extract() specifically when a function-call form is more convenient, such as passing it around as a callable
3. Keep the condition and array arguments in the correct order, condition first, then the array, since reversing them silently produces a different, likely broken result
Tip: np.extract(condition, arr) and directly indexing the array with that same condition do exactly the same thing — boolean indexing is the far more common, idiomatic way to write it in everyday code, so reach for extract() mainly when its function-call form specifically fits your situation better.
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
print(np.extract(arr % 2 == 0, arr))