โณ Loading Python Engine...

๐Ÿ“Š 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

#TopicKey ConceptCore Use Case
1CreationImmutable, (42,) for singleFixed records
2Indexing & Methods.count(), .index() onlyData access
3Packing/Unpackinga, *rest = dataMulti-value returns
4Named Tuplesnamedtuple('Name', fields)Readable records
5Tuples vs ListsHashable, faster, less memoryDict keys, safety
6PatternsSort keys, zip, enumerateIdiomatic Python

1. Tuple Creation & Basics : Immutable Ordered Sequences

๐Ÿ” What is it?

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 MethodExampleNote
Parentheses(1, 2, 3)Standard
Without parens1, 2, 3Comma 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.

In [ ]:

๐Ÿงช Concept Checks: Creation

Q1. Create tuples using all 4 methods: parentheses, commas only, tuple() constructor, and single-element. Print each with type().

In [ ]:

Q2. Prove that (42) is an int but (42,) is a tuple. Print type() for both. Why does this matter?

In [ ]:

Q3. Try to modify a tuple: t = (1, 2, 3); t[0] = 99. Catch the TypeError and print the error message.

In [ ]:

Q4. Compare memory usage of a list vs tuple with the same 1000 elements using sys.getsizeof(). Print the difference.

In [ ]:

Q5. Convert between types: list โ†’ tuple โ†’ list. Start with [10, 20, 30]. Print each conversion and verify contents are equal.

In [ ]:

2. Indexing, Slicing & Methods : Accessing Tuple Data

๐Ÿ” What is it?

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.

OperationSyntaxDescription
Accesst[0], t[-1]By index
Slicet[1:3]Returns new tuple
Countt.count(x)Occurrences of x
Indext.index(x)First position of x
Lengthlen(t)Number of elements
Membershipx in tCheck 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).

In [ ]:

๐Ÿงช 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.

In [ ]:

Q2. Given grades = (85, 92, 78, 85, 95, 85), find: how many times 85 appears, and the index of 95. Print both.

In [ ]:

Q3. Use min(), max(), sum(), len() on scores = (88, 76, 95, 82, 91) to compute basic statistics. Print all.

In [ ]:

Q4. Use sorted() on names = ("Charlie", "Alice", "Bob"). What type does it return? Convert back to tuple.

In [ ]:

Q5. Check membership: is "Python" in langs = ("Python", "Java", "C++", "Go")? Use the in operator. Print result.

In [ ]:

3. Packing & Unpacking : Elegant Data Extraction

๐Ÿ” What is it?
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).

In [ ]:

๐Ÿงช 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.

In [ ]:

Q2. Swap x = 10 and y = 20 using tuple unpacking (one line, no temp variable). Print before and after.

In [ ]:

Q3. Use extended unpacking: given data = (1, 2, 3, 4, 5), extract first element and remaining into first, *rest. Print both.

In [ ]:

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].

In [ ]:

Q5. Given records = [("Alice",85,"A"), ("Bob",72,"B")], iterate with unpacking: for name, score, grade in records:. Print formatted output.

In [ ]:

4. Named Tuples : Self-Documenting Records

๐Ÿ” What is it?
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.

In [ ]:

๐Ÿงช 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.

In [ ]:

Q2. Create a Student named tuple with name, grade, gpa. Create 3 students and find the one with highest GPA. Print the winner.

In [ ]:

Q3. Use ._asdict() to convert a named tuple to a dictionary. Use ._replace() to create a modified copy. Print both.

In [ ]:

Q4. Parse CSV-style data into named tuples: from "Alice,28,NYC" create a Person(name, age, city). Print with field names.

In [ ]:

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.

In [ ]:

5. Tuples vs Lists : When to Use Which

๐Ÿ” What is it?

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."

FeatureTupleList
Mutable?NoYes
SpeedFasterSlower
MemoryLessMore
Hashable?Yes (if contents are)No
Dict key?YesNo
Methods2 (count, index)11+
Use forFixed recordsDynamic 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!

In [ ]:

๐Ÿงช 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.

In [ ]:

Q2. Use a tuple as a dictionary key: create a mapping from (latitude, longitude) to city names for 3 cities. Look up one coordinate.

In [ ]:

Q3. Try adding a list and a tuple to a set. Which works? Which raises TypeError? Explain why (hashability).

In [ ]:

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.

In [ ]:

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.

In [ ]:

6. Professional Tuple Patterns : Real-World Applications

๐Ÿ” What is it?

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

In [ ]:

๐Ÿงช 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.

In [ ]:

Q2. Use enumerate() on fruits = ["apple", "banana", "cherry"] and collect the (index, value) tuples into a list. Print it.

In [ ]:

Q3. Sort employees = [("Bob", "Sales", 50000), ("Alice", "Engineering", 90000), ("Bob", "Engineering", 75000)] by department, then by salary descending.

In [ ]:

Q4. Use zip() to combine keys = ["name", "age", "city"] and values = ["Alice", 28, "NYC"] into a dictionary using dict(zip(...)).

In [ ]:

Q5. Demonstrate tuple comparison: create 5 version tuples like (1, 2, 3) and sort them. Print the sorted order.

In [ ]:

๐Ÿ› ๏ธ 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.

In [ ]:

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.

In [ ]:

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.

In [ ]:

Task 4 (Immutable Config): Create a configuration system using nested named tuples: Config(db=DBConfig(...), api=APIConfig(...)). Show that values cannot be accidentally modified.

In [ ]:

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.

In [ ]:

๐Ÿ’ป 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).

In [ ]:

Q2.

Implement tuple_sort(tuples, key_index) that sorts a list of tuples by the element at key_index.

In [ ]:

Q3.

Write a function group_by_first(pairs) grouping [(1,'a'),(1,'b'),(2,'c')] โ†’ {1:['a','b'], 2:['c']}.

In [ ]:

Q4.

Write a function zip_longest(a, b, fill=None) that zips with fill for shorter list. No itertools.

In [ ]:

Q5.

Write a function unzip(pairs) that converts [(1,'a'),(2,'b')] โ†’ ([1,2],['a','b']). Use zip(*pairs).

In [ ]:

Q6.

Write a function most_common(lst, n) returning n most frequent elements as (element, count) tuples.

In [ ]:

Q7.

Implement a simple Point class using named tuple with distance_to() and repr methods.

In [ ]:

Q8.

Write a function that finds all pairs in a list that sum to a target, returning as tuples.

In [ ]:

Q9.

Write a function merge_records(r1, r2) merging two named tuples, preferring non-None values from r2.

In [ ]:

Q10.

Write a function running_stats(data) yielding (index, value, running_mean, running_max) tuples.

In [ ]:

Q11.

Write a function to convert a dict to a sorted list of (key, value) tuples, sorted by value.

In [ ]:

Q12.

Implement matrix transposition using tuples and zip(). Handle non-rectangular inputs.

In [ ]:

Q13.

Write a function compare_versions(v1, v2) comparing version tuples like (1,2,3) vs (1,3,0).

In [ ]:

Q14.

Write a function pack_ranges(sorted_nums) converting [1,2,3,5,6,8] โ†’ [(1,3),(5,6),(8,8)].

In [ ]:

Q15.

Write a function cartesian_product(a, b) returning all (x, y) pairs from two tuples.

In [ ]:

Q16.

Write code to find the second largest unique element in a tuple without converting to list or sorting.

In [ ]:

Q17.

Write a function rotate_tuple(t, n) rotating a tuple by n positions. (1,2,3,4), 2 โ†’ (3,4,1,2).

In [ ]:

Q18.

Write a function flatten_tuples(nested) flattening ((1, 2), (3, (4, 5))) โ†’ (1, 2, 3, 4, 5). Use recursion.

In [ ]:

Q19.

Write a function weighted_average(data) taking [(value, weight), ...] tuples and computing weighted mean.

In [ ]:

Q20.

Implement a simple Matrix as tuple-of-tuples with get(row, col), transpose(), and add(other) methods.

In [ ]:

Q21.

Write a function sliding_window(data, size) returning tuples of each window: [1,2,3,4], 2 โ†’ [(1,2),(2,3),(3,4)].

In [ ]:

Q22.

Write a function rank(data) that returns (value, rank) tuples, handling ties with average rank.

In [ ]:

Q23.

Write a function safe_unpack(t, n, default=None) that unpacks t into n variables, filling with default if too short.

In [ ]:

Q24.

Implement OrderedPair ensuring first <= second. OrderedPair(5, 3) โ†’ OrderedPair(3, 5).

In [ ]:

Q25.

Write a function tuple_diff(t1, t2) returning elements in t1 but not t2, preserving order and count.

In [ ]:

๐Ÿ“Š Day 5 Executive Summary

#TopicKey TakeawayProfessional Application
1CreationImmutable; trailing comma for singleDatabase records, config
2IndexingSame as lists; only count/index methodsData access
3Packing/Unpacking* for extended; swap with a,b=b,aFunction returns, loops
4Named TuplesNamed fields; _asdict(), _replace()Readable records
5Tuples vs ListsFaster, hashable, dict-key-compatiblePerformance, safety
6PatternsMulti-return, dict.items(), sortingIdiomatic 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.