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:
| Parameter | Type | Description |
|---|---|---|
| tuple | Parenthesized sequence | Immutable ordered collection. |
| set | Curly-brace collection | Unordered collection of distinct hashable values. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Python Lists: Operations, Slicing, and Built-in Methods
Lists are ordered, mutable collections of items. They are one of the most versatile built-in data types in Python.
Python Dictionaries (HashMaps): Key-Value Pairs and Methods
Dictionaries store data values in key:value pairs. They are ordered, changeable, and do not allow duplicate keys.
Python Strings: Slicing, Escaping, and Built-in Methods
Strings in Python are immutable sequences of Unicode characters with rich built-in transformation methods.
Python Online Compiler
Open in Compilra IDE
Run and test Python on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.