We use np.in1d() to quickly check if elements from one list or array appear in another. It helps us find matches easily.
0
0
np.in1d() for membership testing in NumPy
Introduction
Checking which products in a shopping list are available in the store's inventory.
Finding which students from one class attended a school event.
Filtering emails to see which ones are from known contacts.
Identifying common items between two datasets.
Marking which data points belong to a specific group.
Syntax
NumPy
np.in1d(ar1, ar2, assume_unique=False, invert=False)
ar1 is the array of elements to test.
ar2 is the array of elements to check against.
Examples
Checks which elements of [1, 2, 3] are in [2, 3, 4].
NumPy
import numpy as np result = np.in1d([1, 2, 3], [2, 3, 4]) print(result)
Checks which fruits from the first list appear in the second list.
NumPy
import numpy as np result = np.in1d(['apple', 'banana'], ['banana', 'cherry']) print(result)
Returns True for elements in the first array NOT in the second array because of
invert=True.NumPy
import numpy as np result = np.in1d([10, 20, 30], [15, 20, 25], invert=True) print(result)
Sample Program
This program checks which students from the full class list submitted their homework. It prints each student's name with their submission status.
NumPy
import numpy as np # List of students who submitted homework submitted = np.array(['Alice', 'Bob', 'Charlie', 'David']) # List of all students in class all_students = np.array(['Alice', 'Eve', 'Bob', 'Frank', 'Charlie']) # Check who submitted homework submitted_mask = np.in1d(all_students, submitted) # Print results for student, did_submit in zip(all_students, submitted_mask): print(f"{student}: {'Submitted' if did_submit else 'Not Submitted'}")
OutputSuccess
Important Notes
The output is a boolean array showing True where elements of ar1 are in ar2.
Use invert=True to find elements NOT in the second array.
Setting assume_unique=True can speed up the function if you know inputs have no duplicates.
Summary
np.in1d() helps check membership of elements between arrays.
It returns a boolean array matching the first array's shape.
Useful for filtering, matching, and comparing data quickly.