Exercise 5.3
← Previous Module 5: Dictionaries & Sets Next →
Statement
Solution

Python Exercise 5.3: Common Students

Find intersection and symmetric difference between two sets of names.

Your program should:

  • Take two sets of student names (one for math class, one for science class).
  • Find students who are in both classes (intersection).
  • Find students who are in exactly one class (symmetric difference).
  • Print the results clearly.

Sample Interaction:

Input
Output
Alice,Bob,Charlie Bob,Charlie,David
Students in both classes: {'Bob', 'Charlie'} Students in exactly one class: {'Alice', 'David'}

Solution

Here is one way to find common and unique students using sets.

# Get input as comma-separated strings math_students = input("Enter math students (comma-separated): ").split(',') science_students = input("Enter science students (comma-separated): ").split(',') # Convert to sets and strip whitespace math_set = {name.strip() for name in math_students} science_set = {name.strip() for name in science_students} # Find intersection (students in both) both = math_set & science_set # Find symmetric difference (students in exactly one) one_only = math_set ^ science_set # Print results print(f"Students in both classes: {both}") print(f"Students in exactly one class: {one_only}")

Key Concepts:

  • set automatically removes duplicates and allows set operations.
  • & operator finds intersection (common elements).
  • ^ operator finds symmetric difference (elements in one but not both).
  • Set comprehensions can be used to process input lists.
Python 3
Test Console
Run code to see output...

Go Beyond Learning. Get Job-Ready.

Build in-demand skills for today's jobs with free expert-led courses and practical AI tools.

Explore All Courses
Scroll to Top