Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Elements in A Not in B

Find distinct values present in list A but absent from B. Students trace Python membership checks, directional difference, and first-appearance ordering.

IntermediatePhase 4 - Level 4: Aggregation & ComparisonExample 5 of 10
elements-in-a-not-in-b.py
1# Take arrays
2n1 = int(input("Enter size of first array: "))
3arr1 = []
4for i in range(n1):
5 arr1.append(int(input(f"Array1 element {i+1}: ")))
6
7n2 = int(input("Enter size of second array: "))
8arr2 = []
9for i in range(n2):
10 arr2.append(int(input(f"Array2 element {i+1}: ")))
11
12# Find elements in A not in B
13result = []
14for element in arr1:
15 if element not in arr2 and element not in result:
16 result.append(element)
17
18print(f"Elements in A not in B: {result}")

Output

Enter size of first array: 4
Array1 element 1: 1
Array1 element 2: 2
Array1 element 3: 3
Array1 element 4: 4
Enter size of second array: 2
Array2 element 1: 2
Array2 element 2: 3
Elements in A not in B: [1, 4]

In this one

  • Compute a directional difference
  • Exclude a second list
  • Keep distinct output values

How it works

  1. 1

    Visit values from arr1 only.

  2. 2

    Require absence from arr2 and the growing result.

  3. 3

    Append qualifying values in first-appearance order.

Edge cases

Is A minus B the same as B minus A?

Is A minus B the same as B minus A?

Not generally. The direction matters.

What if B is empty?

What if B is empty?

Every distinct value from A is included.

What's going on

The loop considers values from arr1 only. A candidate must be absent from arr2 and absent from the result before it is appended.

This is a directional difference: swapping the input lists can change the answer. Duplicate qualifying values from arr1 appear once. The original input order determines their first-appearance order; no sorting or input mutation occurs.

Is A minus B the same as B minus A? Not generally. The direction matters.

What if B is empty? Every distinct value from A is included.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why test element not in result?

Pick an answer to check it.

Question 2

Is A minus B the same as B minus A?

Pick an answer to check it.

Questions people ask

Is A minus B the same as B minus A?

Not generally. The direction matters.

What if B is empty?

Every distinct value from A is included.

Why test element not in result?

To avoid duplicate output.