Set Operations on Arrays
Reviewed & published by Brayan K
Set operations treat arrays like mathematical sets so you can find shared values, combined values, and differences between two arrays with single functions like intersect1d, union1d, and setdiff1d.
Part of the free NumPy course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
You'll compute intersections, unions, and differences, and test membership element-by-element with np.isin and np.in1d.
What You'll Learn in This Lesson
- Find shared values with np.intersect1d
- Combine values with np.union1d
- Find what is only in A with np.setdiff1d
- Test membership with np.isin and np.in1d
- Why the output is sorted and deduplicated
- Filter one array by another using a mask
1 Intersection & Union
np.intersect1d(a, b) returns the values present in both arrays. np.union1d(a, b) returns every value from either array. Both deduplicate and sort the result, just like sets in math.
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])
np.intersect1d(a, b) # [3 4] -> shared values
np.union1d(a, b) # [1 2 3 4 5 6] -> all values, no dupsimport numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])
# Values in BOTH arrays
print(np.intersect1d(a, b)) # [3 4]
# All values from EITHER array (sorted, unique)
print(np.union1d(a, b)) # [1 2 3 4 5 6]
# Duplicates are collapsed automatically
print(np.intersect1d([3, 3, 4], [4, 4, 5])) # [4]
# ✅ Expected output:
# [3 4]
# [1 2 3 4 5 6]
# [4]2 Difference with np.setdiff1d
np.setdiff1d(a, b) returns the values that are in a but not in b. Order matters: swapping the arguments asks a different question. For "in exactly one of the two", use np.setxor1d.
a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])
np.setdiff1d(a, b) # [1 2] -> in a, not in b
np.setdiff1d(b, a) # [5 6] -> in b, not in a
np.setxor1d(a, b) # [1 2 5 6] -> in exactly oneimport numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])
# In a, but not in b
print(np.setdiff1d(a, b)) # [1 2]
# Order matters!
print(np.setdiff1d(b, a)) # [5 6]
# Symmetric difference: in exactly one array
print(np.setxor1d(a, b)) # [1 2 5 6]
# ✅ Expected output:
# [1 2]
# [5 6]
# [1 2 5 6]3 Membership Tests: np.isin & np.in1d
np.isin(arr, values) asks "is each element of arr present in values?" and returns a boolean mask shaped like arr — ideal for filtering. np.in1d does the same but always returns a flat result. Use the mask to select matching elements.
items = np.array([10, 20, 30, 40])
allowed = [20, 40]
np.isin(items, allowed) # [False True False True]
items[np.isin(items, allowed)] # [20 40] -> keep matches
# isin preserves 2D shape; in1d would flatten
grid = np.array([[1, 2], [3, 4]])
np.isin(grid, [2, 3]) # [[False True], [ True False]]import numpy as np
items = np.array([10, 20, 30, 40, 50])
allowed = [20, 40]
# Boolean mask of membership
mask = np.isin(items, allowed)
print(mask) # [False True False True False]
# Keep only the allowed items
print(items[mask]) # [20 40]
# isin keeps the shape of the first argument
grid = np.array([[1, 2], [3, 4]])
print(np.isin(grid, [2, 3]))
# [[False True]
# [ True False]]
# ✅ Expected output:
# [False True False True False]
# [20 40]
# [[False True]
# [ True False]]🎯 YOUR TURN: Fill in the Blank
Replace ___ with the function that returns values present in both arrays.
import numpy as np
monday = np.array(["Ann", "Bo", "Cy", "Di"])
friday = np.array(["Bo", "Di", "Ed", "Fay"])
# 🎯 YOUR TURN:
# Find the people who attended on BOTH days.
# Hint: shared values = intersection.
both = np.___(monday, friday)
print(both)
# Expected output:
# ['Bo' 'Di']Answer: intersect1d — it returns the sorted values present in both arrays.
! Common Errors (And How to Fix Them)
❌ Expecting setdiff1d to be symmetric
np.setdiff1d(a, b) # NOT the same as setdiff1d(b, a)✅ Fix: put the array you want to keep values from first; use setxor1d for symmetric difference.
❌ Confusing isin argument order
np.isin(allowed, items) # ❌ asks the wrong question✅ Fix: write np.isin(items, allowed) — the first argument is what you test, the second is the set to test against.
❌ Surprised the output is sorted and deduplicated
Set functions never preserve input order or duplicates.
✅ Fix: if you need original order, build a mask with np.isin and index the original array.
🎯 Mini Challenge: Compare Two Carts
Two shoppers have carts. Find the items they both want, everything either wants, and the items unique to the first cart.
import numpy as np
cart_a = np.array(["milk", "eggs", "bread", "cheese"])
cart_b = np.array(["bread", "cheese", "butter", "jam"])
print(np.intersect1d(cart_a, cart_b)) # ['bread' 'cheese']
print(np.union1d(cart_a, cart_b))
# ['bread' 'butter' 'cheese' 'eggs' 'jam' 'milk']
print(np.setdiff1d(cart_a, cart_b)) # ['eggs' 'milk']
# Which of cart_a's items are also in cart_b?
print(np.isin(cart_a, cart_b)) # [False False True True]
# ✅ Expected output:
# ['bread' 'cheese']
# ['bread' 'butter' 'cheese' 'eggs' 'jam' 'milk']
# ['eggs' 'milk']
# [False False True True]❓ Frequently Asked Questions
Lesson complete — sets, mastered!
You can find shared values with intersect1d, combine with union1d, subtract with setdiff1d, and test membership with np.isin to filter one array by another.
Practice quiz
What does np.intersect1d(a, b) return?
- Values present in both arrays
- All values from either array
- Values only in a
- The longer array
Answer: Values present in both arrays. intersect1d returns the sorted unique values present in both arrays.
What does np.union1d(a, b) return?
- Only shared values
- Every value from either array, sorted and unique
- Values only in b
- The first array
Answer: Every value from either array, sorted and unique. union1d returns all values from either array, deduplicated and sorted.
What does np.setdiff1d(a, b) return?
- Shared values
- All values
- Values in a but not in b
- Values in b but not in a
Answer: Values in a but not in b. setdiff1d(a, b) returns the values in a that are not in b.
Is np.setdiff1d symmetric?
- Yes, order never matters
- Only for sorted input
- Only for 2D arrays
- No, swapping arguments changes the result
Answer: No, swapping arguments changes the result. setdiff1d is not symmetric; setdiff1d(a, b) differs from setdiff1d(b, a).
What does np.isin(arr, values) return?
- A boolean mask shaped like arr
- A sorted array
- A count
- A single boolean
Answer: A boolean mask shaped like arr. isin returns a boolean mask the same shape as arr, ideal for filtering.
How do NumPy set functions treat duplicates in their inputs?
- They keep all duplicates
- They remove duplicates (treat input as a set)
- They raise an error
- They double them
Answer: They remove duplicates (treat input as a set). Set functions deduplicate, so [3, 3, 1] behaves like the set {1, 3}.
Which function gives values in exactly one of the two arrays?
- np.intersect1d
- np.union1d
- np.setxor1d
- np.isin
Answer: np.setxor1d. setxor1d returns the symmetric difference: values in exactly one array.
How is the output of np.union1d ordered?
- Input order
- Random
- Sorted ascending
- Reverse sorted
Answer: Sorted ascending. Set operations always return sorted output.
What is the main difference between np.isin and np.in1d?
- np.isin keeps the shape of its first argument; in1d returns flat
- in1d is faster
- isin only works on strings
- They give opposite results
Answer: np.isin keeps the shape of its first argument; in1d returns flat. np.isin preserves the shape of the first argument, while in1d always returns a flat array.
How can you keep original order after a membership test?
- Use union1d
- Build a mask with np.isin and index the original array
- Sort first
- Use setdiff1d
Answer: Build a mask with np.isin and index the original array. Indexing the original array with an np.isin mask preserves its order.
Continue this course
- Previous: Unique Values & Counting
- Next: Rounding & Clipping — Round, floor, ceil, and constrain values into a range with clip
- Quick reference: NumPy cheat sheet
Frequently asked questions
What do the 1d set functions return?
np.intersect1d, np.union1d, and np.setdiff1d all return a sorted 1D array of unique values. The '1d' in the name signals that they flatten their inputs and work on values, not rows. Duplicates are removed automatically and the output is always sorted ascending, just like np.unique.
What is the difference between np.isin and np.in1d?
Both test membership: 'is each element of A present anywhere in B?'. np.in1d returns a flat boolean array, while np.isin keeps the shape of the first argument, so it works naturally on 2D arrays. np.isin is the newer, recommended choice; np.in1d still exists for backward compatibility and behaves the same on 1D input.
Is np.setdiff1d symmetric?
No. setdiff1d(a, b) returns the values in a that are NOT in b, so the order of arguments matters. Swapping them gives a different result. If you want the values that are in exactly one of the two arrays (the symmetric difference), use np.setxor1d instead.
Do these functions remove duplicates and sort?
Yes. Every NumPy set operation treats its inputs as mathematical sets, so it deduplicates the values and returns them sorted. If you pass [3, 3, 1] the function behaves as if you passed [1, 3]. This is convenient but means the output rarely matches the input order.