Set Operations in Python

Level 359 keystrokes

This shows set intersection ({3, 4}) and union ({1, 2, 3, 4, 5, 6}). Sets support mathematical set operations.

Python code

# Create two sets using curly braces {}
# Sets contain unique elements only
1a = {1, 2, 3, 4}
2b = {3, 4, 5, 6}
# & is the intersection operator - elements in BOTH sets
# 3 and 4 are in both a and b
3print(a & b)
# | is the union operator - elements in EITHER set
# Combines all unique elements from both sets
4print(a | b)

Output

{3, 4}
{1, 2, 3, 4, 5, 6}
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • ,× 6
  • (× 2
  • )× 2
  • {× 2
  • }× 2
  • =× 2
  • &× 1
  • |× 1

More Python examples at level 3

← Python typing practice