Python Tuples & Sets: Complete Guide to Immutability, Hashing & Math Sets

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.


Part 1: Python Tuples (Immutable Sequences)

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

Tuple Packing and Unpacking:

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

Part 2: Python Sets (Unique & Unordered Collections)

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()

Mathematical Set Operations in Python

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}

Tuples vs Sets vs Lists Comparison Table

Feature List [] Tuple () Set {}
MutabilityMutableImmutableMutable
OrderingOrdered (Indexed)Ordered (Indexed)Unordered (No Index)
DuplicatesAllowedAllowedForbidden (Unique)
Hashable?NoYes (if elements hashable)No (frozenset is)
Lookup SpeedO(n) linear searchO(n) linear searchO(1) hash lookup

Frequently Asked Questions (FAQ)

Why do tuples consume less memory than lists?

Lists allocate over-provisioned spare memory capacity to support future append() operations efficiently. Because tuples are immutable and fixed-size, Python allocates exactly the memory required without overhead.

How can you remove duplicate items from a list in one line?

You can convert the list to a set and back to a list: unique_list = list(set(original_list)) (Note: this does not guarantee preserving original order).
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!