
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Find elements within range in numpy in Python
Sometime while processing data using the numpy library, we may need to filter out certain numbers in a specific range. This can be achieved by using some in-built methods available in numpy.
With and operator
In this approach we take an numpy array then apply the logical_and function to it. The where clause in numpy is also used to apply the and condition. The result is an array showing the position of the elements satisfying the required range conditions.
import numpy as np A = np.array([5, 9, 11, 4, 31, 27,8]) # printing initial array print("Given Array : ", A) # Range 6 to 15 res = np.where(np.logical_and(A >= 6, A <= 15)) # Result print("Array with condition : ", res)
Output
Running the above code gives us the following result −
Given Array : [ 5 9 11 4 31 27 8] Array with condition : (array([1, 2, 6], dtype=int32),)
Using *
In this approach we use the * operator. It gives the result as actual values instead of the position of the values in the array.
import numpy as np A = np.array([5, 9, 11, 4, 31, 27,8]) # printing initial array print("Given Array : ", A) # Range 6 to 15 res = A [ (A >=6) * (A <= 15)] # Result print("Array with condition : ", res)
Output
Running the above code gives us the following result −
Given Array : [ 5 9 11 4 31 27 8] Array with condition : [ 9 11 8]
- Related Articles
- How to print array elements within a given range using Numpy?
- Program to find number of pairs where elements square is within the given range in Python
- How to create a numpy array within a given range?
- Delete elements in range in Python
- Python – Filter Strings within ASCII range
- Python Program to replace list elements within a range with a given number
- How to find Kaprekar numbers within a given range using Python?
- Python – Extract tuples with elements in Range
- Python - Find the number of prime numbers within a given range of numbers
- Style elements with a value within a specified range with CSS
- Assign range of elements to List in Python
- Prime numbers within a range in JavaScript
- Armstrong number within a range in JavaScript
- Find missing elements of a range in C++
- Python Generate random numbers within a given range and store in a list

Advertisements