0
0
NumPydata~10 mins

np.setdiff1d() for difference in NumPy - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - np.setdiff1d() for difference
Input: array1, array2
Find elements in array1
Check if element NOT in array2
Yes No
Keep element
Return sorted unique difference array
np.setdiff1d() takes two arrays and returns sorted unique elements from the first array that are not in the second.
Execution Sample
NumPy
import numpy as np
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([3, 4, 6])
diff = np.setdiff1d(arr1, arr2)
print(diff)
This code finds elements in arr1 that are not in arr2 and prints them.
Execution Table
StepElement from arr1Is element in arr2?ActionOutput array state
11NoKeep 1[1]
22NoKeep 2[1, 2]
33YesDiscard 3[1, 2]
44YesDiscard 4[1, 2]
55NoKeep 5[1, 2, 5]
6End of arr1-Return sorted unique array[1, 2, 5]
💡 All elements of arr1 checked; output contains elements not in arr2.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
diff[][1][1, 2][1, 2][1, 2][1, 2, 5][1, 2, 5]
Key Moments - 2 Insights
Why does np.setdiff1d return a sorted array even if the input arrays are not sorted?
np.setdiff1d always returns a sorted unique array as shown in the final output in execution_table row 6, ensuring consistent order.
What happens if there are duplicate elements in the first array?
Duplicates are removed in the output because np.setdiff1d returns unique elements only, as implied by the 'unique' in the concept description.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output array state after step 3?
A[1, 2]
B[1, 2, 3]
C[1, 2, 5]
D[3, 4]
💡 Hint
Check the 'Output array state' column at step 3 in execution_table.
At which step does the element '5' get added to the output array?
AStep 2
BStep 5
CStep 4
DStep 3
💡 Hint
Look at the 'Element from arr1' and 'Action' columns in execution_table.
If arr2 was empty, what would the output array be?
AEmpty array []
BOnly elements common to arr1 and arr2
CSame as arr1 but sorted and unique
DOnly elements in arr2
💡 Hint
Recall np.setdiff1d returns elements in arr1 not in arr2; if arr2 is empty, all arr1 elements remain.
Concept Snapshot
np.setdiff1d(array1, array2)
Returns sorted unique elements in array1 not in array2.
Removes duplicates and sorts output.
Useful to find difference between two arrays.
Input arrays can be unsorted.
Full Transcript
np.setdiff1d takes two arrays and finds elements in the first array that are not in the second. It checks each element of the first array, keeps it if it is not in the second array, and discards it otherwise. The result is a sorted array of unique elements. For example, with arr1=[1,2,3,4,5] and arr2=[3,4,6], the output is [1,2,5]. This function always returns sorted unique values, even if inputs are unsorted or have duplicates.