Find Common Elements
Find elements present in both arrays.
IntermediatePhase 4 - Level 4: Aggregation & ComparisonExample 4 of 10
find-common-elements.py
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]
What's going on
Check each element of first array in second.
Key Concepts:
Iterate through first array
Check if exists in second
Avoid duplicates
🔗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