Essential cookies keep authentication working. With your permission, we also use analytics cookies to understand and improve the product. Read our Privacy Policy

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
Home/Questions/Python/Coding/Create a Python program to demonstrate the use of set operations (union, intersection).

Create a Python program to demonstrate the use of set operations (union, intersection).

Python/Codingmedium2 min read

Reviewed by Aditya Kumar · Last reviewed 2026-03-24

Python sets are unordered collections of unique elements, providing highly efficient operations for membership testing and mathematical set operations like union and intersection, which are crucial…

🤖 Analyze Your Answer
Frequency
Low
Asked at 1 company
Category
179
questions in Python/Coding
Difficulty Split
127E|24M|28H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
American Express
Key Concepts Tested
joinpython

Why This Question Matters

This medium-level Python/Coding question appears frequently in data engineering interviews at companies like American Express. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (join, python) will help you answer variations of this question confidently.

How to Approach This

Break this problem into components. Identify the core trade-offs involved, then walk the interviewer through your reasoning step by step. Demonstrate awareness of edge cases and production considerations - this is what separates good answers from great ones. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
407 wordsIncludes code

Python sets are unordered collections of unique elements, providing highly efficient operations for membership testing and mathematical set operations like union and intersection, which are crucial for data cleaning, validation, and analysis.

Mechanics and Use Cases

Python offers both operator-based and method-based syntax for set operations.

* Union (| or .union()): Combines all unique elements from two or more sets.
* Example: set_a | set_b or set_a.union(set_b)
* Use Case: Merging unique identifiers from multiple data sources, consolidating feature lists.
* Intersection (& or .intersection()): Returns elements common to all sets.
* Example: set_a & set_b or set_a.intersection(set_b)
* Use Case: Identifying common customer IDs across different datasets, finding overlapping product categories.
* Difference (- or .difference()): Returns elements present in the first set but not in the second.
* Example: set_a - set_b or set_a.difference(set_b)
* Use Case: Finding new records, identifying users who performed action A but not action B.
* Symmetric Difference (^ or .symmetric_difference()): Returns elements unique to each set (not common to both).
* Example: set_a ^ set_b or set_a.symmetric_difference(set_b)
* Use Case: Highlighting discrepancies between two versions of a dataset.

These operations are highly efficient because Python sets are implemented using hash tables, allowing average O(1) time complexity for element lookups. This makes set operations very fast, often O(min(len(a), len(b))) for intersection, as elements are hashed and compared.

Production Applications and Trade-offs

In data engineering, set operations are fundamental for tasks like deduplication, finding common keys for joins, or identifying data drift. For large datasets, these concepts extend to distributed processing frameworks. For instance, finding common user IDs across two large tables in Spark or Snowflake often leverages hash-based joins, conceptually similar to set intersections, where data is partitioned or clustered to efficiently find overlaps without full scans.

# Identify common customer IDs from two data sources
source_a_ids = {101, 102, 103, 104, 105}
source_b_ids = {103, 104, 106, 107, 108}
common_active_users = source_a_ids.intersection(source_b_ids)
# common_active_users will be {103, 104}

While Python sets are excellent for in-memory operations, for truly massive datasets that don't fit in memory, data engineers apply similar logic using SQL (e.g., INNER JOIN for intersection, LEFT JOIN with WHERE IS NULL for difference) or distributed computing frameworks like PySpark, leveraging their optimized shuffle and partitioning strategies.

In the interview, also mention that the efficiency of set operations makes them ideal for pre-processing steps before more expensive operations like database lookups or complex joins.

⚡
Pro Tip

Pro-Move: Set for dedup in pipelines. Red Flag: List for membership when set fits.

Want all answers as a PDF for offline study?
Seven focused volumes with 750+ in-depth answers — Answer Vault →

Related Python/Coding Questions

easyWhat are traits in Scala, and how are they different from classes?FreemediumWrite a Python function to check if a string is a palindrome.FreeeasyWhat is the difference between a list and a tuple in Python?FreeeasyExplain the difference between shallow copy and deep copy in Python.FreeeasyWrite a Python function to find the first non-repeating character in a string.Free

Level up your prep

Recommended
Educative
Educative Unlimited

800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

Start learning →

Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.

According to DataEngPrep.tech, this is one of the most frequently asked Python/Coding interview questions, reported at 1 company. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

← Back to all questionsMore Python/Coding questions →
Categories
All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
By Company
AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
Interview Guides
All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
Products
AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
Company
About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
© 2026 DataEngPrep.tech. All rights reserved.
AboutBlogContactDisclaimer