๐ Day 05 : Tuples
๐ฏ Enterprise Objective
Tuples are Python's immutable sequences โ faster, safer, and more memory-efficient than lists. Today we master tuple creation, unpacking, named tuples, and professional patterns. Understanding tuples is essential because Python uses them everywhere: function returns, dict iteration, enumerate, and zip.
๐ Strategic Overview
| # | Topic | Key Concept | Core Use Case |
|---|---|---|---|
| 1 | Creation | Immutable, (42,) for single | Fixed records |
| 2 | Indexing & Methods | .count(), .index() only | Data access |
| 3 | Packing/Unpacking | a, *rest = data | Multi-value returns |
| 4 | Named Tuples | namedtuple('Name', fields) | Readable records |
| 5 | Tuples vs Lists | Hashable, faster, less memory | Dict keys, safety |
| 6 | Patterns | Sort keys, zip, enumerate | Idiomatic Python |
1. Tuple Creation & Basics : Immutable Ordered Sequences
A tuple is an ordered, immutable collection created with parentheses () or just commas. Once created, elements cannot be added, removed, or changed. This immutability makes tuples faster, hashable, and safer than lists.
| Creation Method | Example | Note |
|---|---|---|
| Parentheses | (1, 2, 3) | Standard |
| Without parens | 1, 2, 3 | Comma creates tuple |
| Single element | (42,) | Trailing comma required! |
tuple() | tuple([1,2,3]) | Convert from iterable |
| Empty | () or tuple() | Empty tuple |
๐ผ Why Data Analysts Care
โข Database records: Query results are returned as tuples โ immutable rows
โข Function returns: Functions return multiple values as tuples: return x, y
โข Configuration: Immutable settings that should not be accidentally modified
โ ๏ธ Single Element Tuple
(42) is just an integer in parentheses. You need a trailing comma: (42,) to create a single-element tuple.
๐ง Pro Tip
Tuples use less memory than lists and are faster to create and access. Use them for fixed collections.
๐งช Concept Checks: Creation
Q1. Create tuples using all 4 methods: parentheses, commas only, tuple() constructor, and single-element. Print each with type().
Q2. Prove that (42) is an int but (42,) is a tuple. Print type() for both. Why does this matter?
Q3. Try to modify a tuple: t = (1, 2, 3); t[0] = 99. Catch the TypeError and print the error message.
Q4. Compare memory usage of a list vs tuple with the same 1000 elements using sys.getsizeof(). Print the difference.
Q5. Convert between types: list โ tuple โ list. Start with [10, 20, 30]. Print each conversion and verify contents are equal.
2. Indexing, Slicing & Methods : Accessing Tuple Data
Tuples support the same indexing and slicing as lists and strings. Since tuples are immutable, they have only two methods: .count() and .index(). No append, remove, or sort.
| Operation | Syntax | Description |
|---|---|---|
| Access | t[0], t[-1] | By index |
| Slice | t[1:3] | Returns new tuple |
| Count | t.count(x) | Occurrences of x |
| Index | t.index(x) | First position of x |
| Length | len(t) | Number of elements |
| Membership | x in t | Check presence |
๐ผ Why Data Analysts Care
โข Record access: Access database row fields by position: row[0] for ID, row[1] for name
โข Data validation: .count() to verify expected occurrences in fixed datasets
โข Slicing subsets: Extract specific fields from structured records
๐ง Pro Tip
Tuples support all the same built-in functions as lists: len(), min(), max(), sum(), sorted() (returns a list).
๐งช Concept Checks: Indexing & Methods
Q1. Given data = (10, 20, 30, 40, 50), access: first, last, middle element, and a slice of first 3. Print each.
Q2. Given grades = (85, 92, 78, 85, 95, 85), find: how many times 85 appears, and the index of 95. Print both.
Q3. Use min(), max(), sum(), len() on scores = (88, 76, 95, 82, 91) to compute basic statistics. Print all.
Q4. Use sorted() on names = ("Charlie", "Alice", "Bob"). What type does it return? Convert back to tuple.
Q5. Check membership: is "Python" in langs = ("Python", "Java", "C++", "Go")? Use the in operator. Print result.
3. Packing & Unpacking : Elegant Data Extraction
Packing combines values into a tuple. Unpacking extracts tuple elements into individual variables. Python also supports extended unpacking with
* to capture remaining elements.
# Packing
point = 10, 20, 30
# Unpacking
x, y, z = point
# Extended unpacking
first, *rest = [1, 2, 3, 4, 5] # first=1, rest=[2,3,4,5]
first, *mid, last = [1, 2, 3, 4, 5] # first=1, mid=[2,3,4], last=5
๐ผ Why Data Analysts Care
โข Multiple returns: mean, std = compute_stats(data) โ unpack function results
โข Swap variables: a, b = b, a โ Pythonic swap without temp variable
โข Iteration: for name, age in pairs: โ unpack in loops
โข CSV parsing: date, *values = row.split(',') โ separate header from data
โ ๏ธ Mismatched Unpacking
Unpacking requires exact count match: a, b = (1, 2, 3) raises ValueError. Use to absorb extras: a, b, rest = (1, 2, 3).
๐งช Concept Checks: Packing & Unpacking
Q1. Pack three variables name, age, city into a tuple. Then unpack it back into three new variables and print them.
Q2. Swap x = 10 and y = 20 using tuple unpacking (one line, no temp variable). Print before and after.
Q3. Use extended unpacking: given data = (1, 2, 3, 4, 5), extract first element and remaining into first, *rest. Print both.
Q4. Write a function min_max(lst) that returns (min, max) as a tuple. Unpack the result into two variables. Test with [3, 1, 4, 1, 5].
Q5. Given records = [("Alice",85,"A"), ("Bob",72,"B")], iterate with unpacking: for name, score, grade in records:. Print formatted output.
4. Named Tuples : Self-Documenting Records
collections.namedtuple creates tuple subclasses with named fields. You get the immutability and performance of tuples, plus the readability of accessing fields by name instead of index.
from collections import namedtuple
Employee = namedtuple('Employee', ['name', 'age', 'dept'])
emp = Employee('Alice', 30, 'Engineering')
print(emp.name) # Alice (instead of emp[0])
๐ผ Why Data Analysts Care
โข Database rows: Map query results to named fields for readable access
โข Config objects: Immutable configuration with meaningful attribute names
โข API responses: Structure API data with clear field names
โข CSV records: Parse CSV rows into typed, named records
๐ง Pro Tip
Named tuples support ._asdict() to convert to dict, ._replace() to create modified copies, and ._fields to list field names.
๐งช Concept Checks: Named Tuples
Q1. Create a Point named tuple with fields x, y. Create two points and compute the distance between them. Print the result.
Q2. Create a Student named tuple with name, grade, gpa. Create 3 students and find the one with highest GPA. Print the winner.
Q3. Use ._asdict() to convert a named tuple to a dictionary. Use ._replace() to create a modified copy. Print both.
Q4. Parse CSV-style data into named tuples: from "Alice,28,NYC" create a Person(name, age, city). Print with field names.
Q5. Create a list of 5 Product(name, price, qty) named tuples. Write code to find total inventory value (price * qty for all). Print it.
5. Tuples vs Lists : When to Use Which
The choice between tuple and list depends on your intent: use tuples for fixed, heterogeneous records (like database rows) and lists for variable-length, homogeneous collections (like a series of measurements). Tuples signal "this data should not change."
| Feature | Tuple | List |
|---|---|---|
| Mutable? | No | Yes |
| Speed | Faster | Slower |
| Memory | Less | More |
| Hashable? | Yes (if contents are) | No |
| Dict key? | Yes | No |
| Methods | 2 (count, index) | 11+ |
| Use for | Fixed records | Dynamic collections |
๐ผ Why Data Analysts Care
โข Dict keys: Tuples can be dictionary keys (hashable): {(lat, lon): 'city'}
โข Set elements: Tuples can be added to sets; lists cannot
โข Thread safety: Immutable tuples are inherently thread-safe
โข Performance: Tuple creation is ~5-10x faster than list creation
โ ๏ธ Mutable Elements Inside Tuples
A tuple containing a list t = ([1, 2], 3) cannot be hashed (unhashable). The tuple itself is immutable, but the list inside can still be modified: t[0].append(99) works!
๐งช Concept Checks: Tuples vs Lists
Q1. Time the creation of a tuple vs list with 1000 elements using timeit. Print which is faster and by how much.
Q2. Use a tuple as a dictionary key: create a mapping from (latitude, longitude) to city names for 3 cities. Look up one coordinate.
Q3. Try adding a list and a tuple to a set. Which works? Which raises TypeError? Explain why (hashability).
Q4. Show that a tuple containing a list ([1,2], 3) can have its list modified but the tuple itself cannot be reassigned. Demonstrate both.
Q5. Given a dataset scenario: 1000 records, each with 5 fixed fields. Argue whether to store as list-of-tuples or list-of-lists. Test memory with sys.getsizeof.
6. Professional Tuple Patterns : Real-World Applications
Tuples shine in specific patterns: multiple return values, dict items iteration, enumerate results, and zip pairings. Recognizing where Python already uses tuples helps you write more idiomatic code.
Where Python uses tuples implicitly:
โข dict.items() โ (key, value) tuples
โข enumerate() โ (index, value) tuples
โข zip() โ tuples of paired elements
โข Multiple return โ return a, b packs a tuple
โข String % formatting โ '%s is %d' % (name, age)
๐ผ Why Data Analysts Care
โข Multi-value returns: mean, std = get_statistics(data) โ clean function interfaces
โข Sorting with keys: sorted(data, key=lambda x: (x['dept'], -x['salary'])) โ multi-level sort
โข Record comparison: Tuples compare element-by-element: (1, 'b') < (1, 'c') โ True
๐ง Pro Tip
Tuples compare lexicographically: element by element, left to right. Use this for multi-level sorting: sorted(items, key=lambda x: (x.dept, -x.salary)).
๐งช Concept Checks: Patterns
Q1. Write a function stats(data) that returns (min, max, mean, median) as a tuple. Unpack the result and print each value.
Q2. Use enumerate() on fruits = ["apple", "banana", "cherry"] and collect the (index, value) tuples into a list. Print it.
Q3. Sort employees = [("Bob", "Sales", 50000), ("Alice", "Engineering", 90000), ("Bob", "Engineering", 75000)] by department, then by salary descending.
Q4. Use zip() to combine keys = ["name", "age", "city"] and values = ["Alice", 28, "NYC"] into a dictionary using dict(zip(...)).
Q5. Demonstrate tuple comparison: create 5 version tuples like (1, 2, 3) and sort them. Print the sorted order.
๐ ๏ธ Professional Practice Tasks
Theory is useless without muscle memory. Complete these tasks to solidify your understanding.
Task 1 (Record Processor): Create 5 employee records as named tuples (name, dept, salary). Write code to: find highest salary, average salary by department, and list employees sorted by salary.
Task 2 (Coordinate System): Write functions distance(p1, p2) and midpoint(p1, p2) that take (x, y) tuples. Test with 3 pairs of points and print formatted results.
Task 3 (Data Converter): Write a function csv_to_records(csv_text) that takes a multi-line CSV string, parses it into a list of named tuples, and returns them. Test with 5 rows of data.
Task 4 (Immutable Config): Create a configuration system using nested named tuples: Config(db=DBConfig(...), api=APIConfig(...)). Show that values cannot be accidentally modified.
Task 5 (Frequency Analyzer): Write a function top_n(data, n) that takes a list of values, counts frequencies using tuples (value, count), sorts by count, and returns the top n. Test with a word list.
๐ป Pure Coding Interview Questions
Q1.
Write a function that takes a list of (x, y) tuples and returns the point closest to the origin (0, 0).
Q2.
Implement tuple_sort(tuples, key_index) that sorts a list of tuples by the element at key_index.
Q3.
Write a function group_by_first(pairs) grouping [(1,'a'),(1,'b'),(2,'c')] โ {1:['a','b'], 2:['c']}.
Q4.
Write a function zip_longest(a, b, fill=None) that zips with fill for shorter list. No itertools.
Q5.
Write a function unzip(pairs) that converts [(1,'a'),(2,'b')] โ ([1,2],['a','b']). Use zip(*pairs).
Q6.
Write a function most_common(lst, n) returning n most frequent elements as (element, count) tuples.
Q7.
Implement a simple Point class using named tuple with distance_to() and repr methods.
Q8.
Write a function that finds all pairs in a list that sum to a target, returning as tuples.
Q9.
Write a function merge_records(r1, r2) merging two named tuples, preferring non-None values from r2.
Q10.
Write a function running_stats(data) yielding (index, value, running_mean, running_max) tuples.
Q11.
Write a function to convert a dict to a sorted list of (key, value) tuples, sorted by value.
Q12.
Implement matrix transposition using tuples and zip(). Handle non-rectangular inputs.
Q13.
Write a function compare_versions(v1, v2) comparing version tuples like (1,2,3) vs (1,3,0).
Q14.
Write a function pack_ranges(sorted_nums) converting [1,2,3,5,6,8] โ [(1,3),(5,6),(8,8)].
Q15.
Write a function cartesian_product(a, b) returning all (x, y) pairs from two tuples.
Q16.
Write code to find the second largest unique element in a tuple without converting to list or sorting.
Q17.
Write a function rotate_tuple(t, n) rotating a tuple by n positions. (1,2,3,4), 2 โ (3,4,1,2).
Q18.
Write a function flatten_tuples(nested) flattening ((1, 2), (3, (4, 5))) โ (1, 2, 3, 4, 5). Use recursion.
Q19.
Write a function weighted_average(data) taking [(value, weight), ...] tuples and computing weighted mean.
Q20.
Implement a simple Matrix as tuple-of-tuples with get(row, col), transpose(), and add(other) methods.
Q21.
Write a function sliding_window(data, size) returning tuples of each window: [1,2,3,4], 2 โ [(1,2),(2,3),(3,4)].
Q22.
Write a function rank(data) that returns (value, rank) tuples, handling ties with average rank.
Q23.
Write a function safe_unpack(t, n, default=None) that unpacks t into n variables, filling with default if too short.
Q24.
Implement OrderedPair ensuring first <= second. OrderedPair(5, 3) โ OrderedPair(3, 5).
Q25.
Write a function tuple_diff(t1, t2) returning elements in t1 but not t2, preserving order and count.
๐ Day 5 Executive Summary
| # | Topic | Key Takeaway | Professional Application |
|---|---|---|---|
| 1 | Creation | Immutable; trailing comma for single | Database records, config |
| 2 | Indexing | Same as lists; only count/index methods | Data access |
| 3 | Packing/Unpacking | * for extended; swap with a,b=b,a | Function returns, loops |
| 4 | Named Tuples | Named fields; _asdict(), _replace() | Readable records |
| 5 | Tuples vs Lists | Faster, hashable, dict-key-compatible | Performance, safety |
| 6 | Patterns | Multi-return, dict.items(), sorting | Idiomatic Python |
โ Instructor's End-of-Day Checklist
โข [ ] I understand tuple immutability and when to prefer tuples over lists.
โข [ ] I can use packing/unpacking including extended * syntax.
โข [ ] I can create and use named tuples for readable records.
โข [ ] I know that tuples are hashable and can be dict keys.
โข [ ] I understand lexicographic tuple comparison for multi-level sorting.
โข [ ] I have completed all 5 practice tasks.
โข [ ] I have reviewed all 25 interview questions.