Python Tuples & Sets
PythonTuples are like lists but immutable (can't change). Sets are unordered collections with no duplicates.
Key Points
- Tuples use parentheses
()— immutable, faster than lists - Sets use curly braces
{}— no duplicates, unordered - Tuples are great for fixed data (coordinates, RGB colors)
- Sets are perfect for removing duplicates and math operations
- Set operations:
union,intersection,difference
Example — PYTHON
# Tuples
coordinates = (28.6139, 77.2090) # Delhi
print(f"Lat: {coordinates[0]}, Lon: {coordinates[1]}")
# Tuple unpacking
name, age, city = ("Rahul", 20, "Pune")
print(f"{name} is {age} from {city}")
# Tuple is immutable
# coordinates[0] = 19.07 # This would cause an error!
# Sets — no duplicates
numbers = {1, 2, 3, 2, 1, 4, 5, 4}
print(f"Unique: {numbers}")
# Remove duplicates from list
roll_numbers = [101, 102, 101, 103, 102, 104]
unique_rolls = list(set(roll_numbers))
print(f"Unique rolls: {unique_rolls}")
# Set operations
python_students = {"Rahul", "Priya", "Amit", "Sara"}
java_students = {"Amit", "Sara", "Vikram", "Neha"}
# Who studies both?
both = python_students & java_students
print(f"Both: {both}")
# All students
all_students = python_students | java_students
print(f"All: {all_students}")
# Only Python
only_python = python_students - java_students
print(f"Only Python: {only_python}") Result
Lat: 28.6139, Lon: 77.209
Rahul is 20 from Pune
Unique: {1, 2, 3, 4, 5}
Unique rolls: [101, 102, 103, 104]
Both: {'Amit', 'Sara'}
All: {'Rahul', 'Priya', 'Amit', 'Sara', 'Vikram', 'Neha'}
Only Python: {'Rahul', 'Priya'}
Rahul is 20 from Pune
Unique: {1, 2, 3, 4, 5}
Unique rolls: [101, 102, 103, 104]
Both: {'Amit', 'Sara'}
All: {'Rahul', 'Priya', 'Amit', 'Sara', 'Vikram', 'Neha'}
Only Python: {'Rahul', 'Priya'}