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.
1# Take arrays2n1 = int(input("Enter size of first array: "))3arr1 = []4for i in range(n1):5 arr1.append(int(input(f"Array1 element {i+1}: ")))67n2 = int(input("Enter size of second array: "))8arr2 = []9for i in range(n2):10 arr2.append(int(input(f"Array2 element {i+1}: ")))1112# Find elements in A not in B13result = []14for element in arr1:15 if element not in arr2 and element not in result:16 result.append(element)1718print(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
Visit values from arr1 only.
- 2
Require absence from arr2 and the growing result.
- 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.
๐Related Content
- ๐
Phase 4 - Learn Concepts
Review Phase 4 concepts and explanations
- ๐
Phase 4 - Quiz
Test your Phase 4 understanding with quiz questions
- ๐ป
Phase 4 - All Practice Problems
Explore all practice problems for Phase 4
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum