Day 9: Mastering Tuples and Sets in Python
In this session, we explore two important Python data structures:
- Tuples: used for fixed, ordered data
- Sets: used for unique, unordered data
Understanding these will help you write more efficient and structured programs.
What is a Tuple?
A tuple is an ordered, immutable collection of elements.
t = (10, 20, 30)
print(t)
Key Characteristics:
- Ordered (supports indexing)
- Immutable (cannot be modified after creation)
- Allows duplicate values
Tuple vs List
| Feature | Tuple | List |
|---|---|---|
| Mutability | Immutable | Mutable |
| Syntax | () | [] |
| Performance | Faster | Slightly slower |
| Use Case | Fixed data | Dynamic data |
# List (mutable)
lst = [1, 2, 3]
lst[0] = 100 # allowed
# Tuple (immutable)
tup = (1, 2, 3)
# tup[0] = 100 # Error
Why Use Tuples?
Tuples are preferred when:
- Data should not change
- Performance is important
- Data integrity must be maintained
coordinates = (23.5, 77.2)
print(coordinates)
Accessing Tuple Elements
t = (10, 20, 30, 40)
print(t[0]) # 10
print(t[-1]) # 40
Tuple Packing and Unpacking
Packing
t = 10, 20, 30
Unpacking
a, b, c = (10, 20, 30)
print(a, b, c)
Extended Unpacking
a, *b = (1, 2, 3, 4, 5)
print(a) # 1
print(b) # [2, 3, 4, 5]
Functions Return Tuples Automatically
def get_values():
return 1, 2, 3
result = get_values()
print(result)
a, b, c = get_values()
print(a, b, c)
Tuple Methods
t = (1, 2, 2, 3)
print(t.count(2))
print(t.index(3))
Tuple Use Cases
- Returning multiple values from functions
- Storing fixed configurations
- Using tuples as dictionary keys
data = {
(1, 2): "Point A",
(3, 4): "Point B"
}
What is a Set?
A set is an unordered collection of unique elements.
s = {1, 2, 3}
print(s)
Key Characteristics:
- Unordered
- No duplicate elements
- Mutable
Why Sets Are Useful?
- Remove duplicates
- Fast membership checking
- Perform mathematical operations
nums = [1, 2, 2, 3, 4]
unique = set(nums)
print(unique)
Creating Sets
s1 = {1, 2, 3}
s2 = set([4, 5, 6])
Adding and Removing Elements
s = {1, 2, 3}
s.add(4)
s.remove(2)
s.discard(10) # no error if element not present
Set Operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union
print(a & b) # Intersection
print(a - b) # Difference
print(a ^ b) # Symmetric Difference
Membership Testing
s = {1, 2, 3}
print(2 in s)
Iterating Over a Set
for i in {10, 20, 30}:
print(i)
Set Methods
s = {1, 2}
s.update([3, 4])
s.clear()
Set Use Cases
- Removing duplicates
- Finding common elements
- Filtering datasets
- Fast lookups
a = [1, 2, 3]
b = [2, 3, 4]
print(set(a) & set(b))
Tuple vs Set Summary
| Feature | Tuple | Set |
|---|---|---|
| Order | Ordered | Unordered |
| Mutability | Immutable | Mutable |
| Duplicates | Allowed | Not allowed |
| Use Case | Fixed data | Unique elements |
Practice Questions
Basic
- Create a tuple and print its first and last element
- Convert a list into a tuple
- Create a set and print all its elements
- Add an element to a set
- Remove duplicates from a list using a set
Intermediate
- Unpack a tuple into three variables
- Count occurrences of an element in a tuple
- Find common elements between two lists using sets
- Check if an element exists in a set
- Perform union and intersection on two sets
Advanced
- Swap two variables using tuple unpacking
- Combine two lists and extract only unique elements
- Find elements present in one set but not in another
- Use a tuple as a dictionary key and retrieve its value
- Remove duplicate words from a sentence using a set
Final Takeaways
- Tuples are best suited for fixed and unchangeable data
- Sets are ideal for handling unique elements and performing fast operations
- Choosing the right data structure improves both performance and code clarity
.png)
.png)
