Find Common Elements
Find distinct values shared by two lists. Students combine membership with duplicate suppression and preserve first-list order in the common-value result.
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 common elements13common = []14for element in arr1:15 if element in arr2 and element not in common:16 common.append(element)1718print(f"Common elements: {common}")
Output
Enter size of first array: 4 Array1 element 1: 1 Array1 element 2: 2 Array1 element 3: 3 Array1 element 4: 2 Enter size of second array: 3 Array2 element 1: 2 Array2 element 2: 3 Array2 element 3: 4 Common elements: [2, 3]
In this one
- Find shared values
- Suppress duplicate output
- Preserve first-list ordering
How it works
- 1
Visit each value in arr1.
- 2
Require membership in arr2 and absence from common.
- 3
Append qualifying values once and print common.
Edge cases
Do repeated shared values appear twice?
Do repeated shared values appear twice?
No. common suppresses repeated output.
What if either list is empty?
What if either list is empty?
There are no shared values.
What's going on
The loop scans arr1. A value is appended only if it exists in arr2 and has not already been placed in common.
The second test prevents duplicate output when arr1 repeats a shared value. The result follows first appearance in arr1 rather than sorted order. This uses list membership searches, so larger inputs can require repeated scans.
Do repeated shared values appear twice? No. common suppresses repeated output.
What if either list is empty? There are no shared values.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which list determines result order?
Pick an answer to check it.
Question 2
Do repeated shared values appear twice?
Pick an answer to check it.
Questions people ask
Do repeated shared values appear twice?
No. common suppresses repeated output.
What if either list is empty?
There are no shared values.
Which list determines result order?
arr1.
๐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