In this class, we explore two fundamental collection types: Tuples (immutable sequences) and Sets (unique, unordered mathematical collections). Both data structures play pivotal roles in writing performant, bug-resistant Python applications and are staple subjects in university BCA and engineering examinations.
A tuple is an ordered collection of elements enclosed in parentheses (). Once created, a tuple's elements cannot be modified, replaced, or deleted:
# Creating tuples
location = (28.7041, 77.1025) # Delhi latitude & longitude
single_item_tuple = (50,) # Trailing comma required!
# Accessing elements via indexing & slicing:
print(location[0]) # 28.7041
print(location[-1]) # 77.1025
Tuples allow elegant multiple value packing and unpacking:
# Tuple Packing:
record = 101, "Aman Gupta", "Computer Science" # Parentheses optional!
# Tuple Unpacking:
roll_no, student_name, branch = record
print(f"Roll: {roll_no}, Name: {student_name}, Branch: {branch}")
# Extended Unpacking with * (PEP 3132):
scores = [90, 85, 78, 92, 88]
first, *middle, last = scores
print(f"First: {first}, Middle: {middle}, Last: {last}")
# First: 90, Middle: [85, 78, 92], Last: 88
A set is an unordered collection of unique, hashable objects enclosed in curly brackets {}. Sets automatically eliminate duplicates and offer O(1) average lookup time:
# Creating a set:
vowels = {'a', 'e', 'i', 'o', 'u', 'a', 'e'}
print("Unique vowels:", vowels) # {'a', 'e', 'i', 'o', 'u'}
# Creating an empty set (MUST use set(), because {} creates an empty dict!):
empty_set = set()
Python sets support all operations from set mathematics:
set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}
# 1. Union (|): Elements in either A or B
print("Union:", set_a | set_b)
# {1, 2, 3, 4, 5, 6, 7, 8}
# 2. Intersection (&): Elements present in BOTH A and B
print("Intersection:", set_a & set_b)
# {4, 5}
# 3. Difference (-): Elements in A but NOT in B
print("Difference (A - B):", set_a - set_b)
# {1, 2, 3}
# 4. Symmetric Difference (^): Elements in A or B, but NOT both
print("Symmetric Difference:", set_a ^ set_b)
# {1, 2, 3, 6, 7, 8}
| Feature | List [] |
Tuple () |
Set {} |
|---|---|---|---|
| Mutability | Mutable | Immutable | Mutable |
| Ordering | Ordered (Indexed) | Ordered (Indexed) | Unordered (No Index) |
| Duplicates | Allowed | Allowed | Forbidden (Unique) |
| Hashable? | No | Yes (if elements hashable) | No (frozenset is) |
| Lookup Speed | O(n) linear search | O(n) linear search | O(1) hash lookup |
append() operations efficiently. Because tuples are immutable and fixed-size, Python allocates exactly the memory required without overhead.
unique_list = list(set(original_list)) (Note: this does not guarantee preserving original order).