Python Tuples(advanced)
Table of Contents
Description
A tuple is an immutable, ordered collection of items. Beyond basics, advanced tuple concepts include:
Tuple packing/unpacking
Nested tuples
Tuples as dictionary keys
Enumerate with tuples
Using zip() with tuples
Immutability use-cases
Named tuples
Prerequisites
- Basic knowledge of:
Tuple creation and indexing
Lists and loops
Dictionaries
Functions and argument unpacking
Examples
Here's a simple program in Python:
✅ Tuple Packing and Unpacking # Packing person = ("Alice", 25, "Engineer") # Unpacking name, age, profession = person print(name) # Alice print(profession) # Engineer ✅ Nested Tuples # Tuple inside another tuple data = ("Python", (3, 8, 10)) # Access inner tuple's 2nd element print(data[1][1]) # Output: 8 ✅ Tuple as Dictionary Key # Tuples can be dictionary keys because they are immutable coordinates = {} # Assign a value to a tuple key coordinates[(10, 20)] = "Location A" print(coordinates[(10, 20)]) # Location A ✅ Using enumerate() with Tuples # Enumerate returns (index, value) pairs as tuples fruits = ("apple", "banana", "mango") for index, fruit in enumerate(fruits): print(index, fruit) # Output: # 0 apple # 1 banana # 2 mango ✅ Using zip() to Create Tuples names = ["A", "B"] scores = [90, 95] # zip creates tuple pairs result = tuple(zip(names, scores)) print(result) # (('A', 90), ('B', 95)) ✅ Tuples in Function Arguments def display_info(*args): # args is a tuple of arguments for item in args: print(item) display_info("Python", 3.10, "Stable") ✅ Named Tuples (from collections) from collections import namedtuple # Define a named tuple Person = namedtuple("Person", "name age") # Create a person object p1 = Person(name="Alice", age=25) # Access by name print(p1.name) # AliceReal-World Applications
Representing coordinate points, RGB values, and fixed data
Using tuples as keys in caches (like LRU or memoization)
Storing multi-value immutable records (e.g., DB rows)
Fast and memory-efficient alternative to lists
Where topic Can Be Applied
Data science: Tuple returns in NumPy, Pandas
APIs: Unchanging data like configurations, credentials
AI/ML: Storing fixed-length vectors or hyperparameters
Web dev: URL pattern definitions (e.g., ("GET", "/api/user"))>
Resources
WatchTopic video source
A comprehensive video
VisitPython pdf
pdf on topic
Interview Questions
Why are tuples immutable?
Can tuples be used as dictionary keys?
What is tuple unpacking?
What is a namedtuple and when should it be used?
Difference between a tuple and a list?
How is *args related to tuples in Python?