Python:Python Tuples and Sets: Immutability and Unique Collections
Python•Tuples & Sets

Python Tuples and Sets: Immutability and Unique Collections

Tuples guarantee integrity by preventing modification after instantiation. Sets eliminate duplicates and support union, intersection, and difference operations.

Syntax

my_tuple = (item1, item2, ...) my_set = {item1, item2, ...} set_union = set_a | set_b

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
tupleParenthesized sequenceImmutable ordered collection.
setCurly-brace collectionUnordered collection of distinct hashable values.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Python locally:

# 1. Tuples & Multiple Return / Unpacking
coordinates = (37.7749, -122.4194)
lat, lon = coordinates
print(f"Latitude: {lat}, Longitude: {lon}")

# 2. Sets: Automatic Deduplication & Set Math
roles_alice = {"Developer", "Reviewer", "Tester"}
roles_bob = {"Reviewer", "Deployer"}

# Set operations: Union, Intersection, Difference
common_roles = roles_alice & roles_bob
all_roles = roles_alice | roles_bob
alice_exclusive = roles_alice - roles_bob

print(f"\nCommon Roles (&):    {common_roles}")
print(f"All Unique Roles (|): {all_roles}")
print(f"Alice Only (-):       {alice_exclusive}")
Expected Output:
Latitude: 37.7749, Longitude: -122.4194

Common Roles (&):    {'Reviewer'}
All Unique Roles (|): {'Developer', 'Reviewer', 'Deployer', 'Tester'}
Alice Only (-):       {'Developer', 'Tester'}

How It Works: Step-by-Step

  • Lines 2-4: Creates tuple and unpacks components into distinct variables.
  • Lines 7-8: Initializes sets with unique string identifiers.
  • Lines 11-13: Computes set intersection (&), union (|), and difference (-).

Key Concepts

  • Tuples cannot be altered once created; attempting assignment throws TypeError.
  • Sets automatically discard duplicate entries upon insertion.
  • Sets provide O(1) membership testing with the in keyword.

Common Mistake: Creating a single-element tuple without a trailing comma

(42) is evaluated as integer 42 inside parentheses. Use (42,) for a single-element tuple.

❌ Incorrect
x = (42) # type(x) is int, not tuple!
✅ Correct
x = (42,) # type(x) is tuple

Related Python Tutorials & Compiler

Run and test Python on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Python Online Compiler