How do they achieve internally that you are able to pass something like x > 5 into a method?

The short answer is that they don't.

Any sort of logical operation on a numpy array returns a boolean array. (i.e. __gt__, __lt__, etc all return boolean arrays where the given condition is true).

E.g.

x = np.arange(9).reshape(3,3)
print x > 5

yields:

array([[False, False, False],
       [False, False, False],
       [ True,  True,  True]], dtype=bool)

This is the same reason why something like if x > 5: raises a ValueError if x is a numpy array. It's an array of True/False values, not a single value.

Furthermore, numpy arrays can be indexed by boolean arrays. E.g. x[x>5] yields [6 7 8], in this case.

Honestly, it's fairly rare that you actually need numpy.where but it just returns the indicies where a boolean array is True. Usually you can do what you need with simple boolean indexing.

Answer from Joe Kington on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › numpy › numpy-where-in-python
numpy.where() in Python - GeeksforGeeks
September 30, 2025 - With only condition: returns a tuple of index arrays (one per dimension). With x and y: returns a new array choosing from x where True, y where False (supports broadcasting and dtype rules).
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.where.html
numpy.where — NumPy v2.5.dev0 Manual
Return elements chosen from x or y depending on condition · When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses. The rest of this documentation covers only the ...
Discussions

How does python numpy.where() work? - Stack Overflow
There can also be overhead in some cases using the __getitem__ syntax of [] over either numpy.where or numpy.take. Since __getitem__ has to also support slicing, there's some overhead. I've seen noticeable speed differences when working with the Python Pandas data structures and logically indexing ... More on stackoverflow.com
🌐 stackoverflow.com
`where` clauses in List comprehension - Ideas - Discussions on Python.org
Has the where clause, as used in Haskell, ever been explored for Python List comprehension? For example, text_numbers = [ "one", "two", "three", .... ] # Print pair numbers print( [ x for x in text_numbers … More on discuss.python.org
🌐 discuss.python.org
0
November 9, 2022
How does np.where() work?
Have you read the docs? https://numpy.org/doc/stable/reference/generated/numpy.where.html The explanations and examples there seem very clear to me(, considering this is about multi dimensional arrays). More on reddit.com
🌐 r/learnpython
5
4
March 31, 2022
How can I find where Python is installed on Windows? - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I want to find out my Python installation path on Windows. More on stackoverflow.com
🌐 stackoverflow.com
🌐
StrataScratch
stratascratch.com › blog › exploring-numpy-where-in-python
Exploring NumPy where() in Python for Conditional Operations - StrataScratch
September 17, 2025 - With three arguments: when you ... large arrays · Let's start with something simple. When you offer np.where() a condition, it gives you the indices where that condition is true....
🌐
W3Schools
w3schools.com › python › pandas › ref_df_where.asp
Pandas DataFrame where() Method
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
🌐
IONOS
ionos.com › digital guide › websites › web development › python np.where method
What is np.where in Python? - IONOS
January 2, 2025 - The Python function np.where() is a powerful method from the NumPy library and is used for selecting elements from an array. It iden­ti­fies and extracts elements that meet a certain condition and then returns indices or values that cor­re­spond ...
Top answer
1 of 4
78

How do they achieve internally that you are able to pass something like x > 5 into a method?

The short answer is that they don't.

Any sort of logical operation on a numpy array returns a boolean array. (i.e. __gt__, __lt__, etc all return boolean arrays where the given condition is true).

E.g.

x = np.arange(9).reshape(3,3)
print x > 5

yields:

array([[False, False, False],
       [False, False, False],
       [ True,  True,  True]], dtype=bool)

This is the same reason why something like if x > 5: raises a ValueError if x is a numpy array. It's an array of True/False values, not a single value.

Furthermore, numpy arrays can be indexed by boolean arrays. E.g. x[x>5] yields [6 7 8], in this case.

Honestly, it's fairly rare that you actually need numpy.where but it just returns the indicies where a boolean array is True. Usually you can do what you need with simple boolean indexing.

2 of 4
25

Old Answer it is kind of confusing. It gives you the LOCATIONS (all of them) of where your statment is true.

so:

>>> a = np.arange(100)
>>> np.where(a > 30)
(array([31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
       48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
       65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
       82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98,
       99]),)
>>> np.where(a == 90)
(array([90]),)

a = a*40
>>> np.where(a > 1000)
(array([26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
       43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
       60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
       77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93,
       94, 95, 96, 97, 98, 99]),)
>>> a[25]
1000
>>> a[26]
1040

I use it as an alternative to list.index(), but it has many other uses as well. I have never used it with 2D arrays.

http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

New Answer It seems that the person was asking something more fundamental.

The question was how could YOU implement something that allows a function (such as where) to know what was requested.

First note that calling any of the comparison operators do an interesting thing.

a > 1000
array([False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True`,  True,  True,  True,  True,  True,  True,  True,  True,  True], dtype=bool)`

This is done by overloading the "__gt__" method. For instance:

>>> class demo(object):
    def __gt__(self, item):
        print item


>>> a = demo()
>>> a > 4
4

As you can see, "a > 4" was valid code.

You can get a full list and documentation of all overloaded functions here: http://docs.python.org/reference/datamodel.html

Something that is incredible is how simple it is to do this. ALL operations in python are done in such a way. Saying a > b is equivalent to a.gt(b)!

🌐
DataCamp
datacamp.com › doc › numpy › where
NumPy where()
In this syntax, `condition` is a boolean array, and `x` and `y` are optional arrays or scalars from which elements are selected based on `condition`. When only `condition` is provided, `where()` returns the indices of elements where `condition` is `True`.
Find elsewhere
🌐
Programiz
programiz.com › python-programming › numpy › methods › where
NumPy where()
If we pass a single argument (test condition) to numpy.where(), it tells us where in a given array the given condition is met by returning the indices.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-numpy-where
How to use Python numpy.where() Method | DigitalOcean
August 3, 2022 - In Python, we can use the numpy.where() function to select elements from a numpy array, based on a condition.
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.where.html
numpy.where — NumPy v2.2 Manual
Return elements chosen from x or y depending on condition · When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses. The rest of this documentation covers only the ...
🌐
Vultr Docs
docs.vultr.com › python › third-party › numpy › where
Python Numpy where() - Conditional Element Search | Vultr Docs
December 30, 2024 - The numpy.where() function in Python offers a robust way to perform conditional element searches within arrays, enabling efficient and selective data handling. From simple condition checks to complex analyses involving multiple conditions and ...
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.where.html
pandas.DataFrame.where — pandas 3.0.2 documentation
Where cond is True, keep the original value. Where False, replace with corresponding value from other. If cond is callable, it is computed on the Series/DataFrame and should return boolean Series/DataFrame or array. The callable must not change input Series/DataFrame (though pandas doesn’t check it).
🌐
Python.org
discuss.python.org › ideas
`where` clauses in List comprehension - Ideas - Discussions on Python.org
November 9, 2022 - Has the where clause, as used in Haskell, ever been explored for Python List comprehension? For example, text_numbers = [ "one", "two", "three", .... ] # Print pair numbers print( [ x for x in text_numbers if num % 2 == 0 where num = get_number_from_text(x) ] )
🌐
Reddit
reddit.com › r/learnpython › how does np.where() work?
r/learnpython on Reddit: How does np.where() work?
March 31, 2022 -

My understanding of np.where() was so far as sort of an arg container for .loc. However in the example below, .loc works, but not when np.where is used as arg. Why is that happening?

df=pd.DataFrame({'Name':['Tom', 'Mia', 'Sam'], 'Age':[15, 26, 32]}, index=['A','B','C'])

print(df.loc[(df['Age']>28)&(df['Name'].str.startswith('S')])

k=np.where((df['Age']>28)&(df['Name'].str.startswith('S'))

print(df.loc[k])

🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.where.html
numpy.where — NumPy v2.4 Manual
Return elements chosen from x or y depending on condition · When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses. The rest of this documentation covers only the ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-pandas-dataframe-where
Pandas DataFrame.where()-Python - GeeksforGeeks
June 24, 2025 - Interview Prep · Python Tutorial ... Flask · Last Updated : 24 Jun, 2025 · DataFrame.where() function replace values in a DataFrame based on a condition....
🌐
Medium
medium.com › @shouke.wei › mastering-np-where-and-pd-where-in-python-conditional-selection-made-easy-8a8666094040
Mastering np.where() and pd.where() in Python: Conditional Selection Made Easy | by Dr. Shouke Wei | Medium
November 2, 2025 - When working with large datasets or numerical arrays in Python, it’s common to need conditional logic — selecting, replacing, or filtering values based on specific conditions. Two powerful functions, np.where() (from NumPy) and pd.where() (from Pandas), make this task elegant, efficient, and expressive.
🌐
Cherry Servers
cherryservers.com › home › blog › cloud computing › how to use numpy.where function [with examples]
How to Use numpy.where Function [With Examples]
November 7, 2025 - Numpy.where is a powerful tool for conditional element selection or transformation on NumPy arrays. It is commonly used in data processing, analysis, and algorithms. In this tutorial, we look at how you can use the numpy.where function and bring ...