Lists & Tuples: Dynamic Sequences and Immutability

Module 2 • Session 15 • Allocation: 1 Contact Hr

lists tuples mutability indexing & slicing sys.getsizeof

Lists and tuples are fundamental sequence data types in Python designed to store collections of elements. While both support positional indexing, slicing, and iteration, their fundamental difference lies in mutability, memory allocation strategy, and intended semantic usage.

1. Comparison & Core Differences

Selecting between lists and tuples directly impacts both software safety and runtime execution performance.

Feature List (list) Tuple (tuple)
Syntax Enclosed in square brackets [1, 2, 3] Enclosed in parentheses (1, 2, 3)
Mutability Mutable: Elements can be altered, added, or removed. Immutable: Elements cannot be modified after assignment.
Memory Allocation Over-allocates dynamic contiguous memory for $O(1)$ appends. Allocates fixed memory size exact to payload dimensions.
Dictionary Keys Unhashable (cannot be used as dict key or set item). Hashable (if all stored elements are also hashable).

2. Sequence Indexing and Slicing Mechanics

Both lists and tuples adhere to standard zero-based indexing and step slicing using the pattern sequence[start:stop:step].

data = [10, 20, 30, 40, 50, 60] # Positive Indexing print(data[0]) # Output: 10 print(data[3]) # Output: 40 # Negative Indexing print(data[-1]) # Output: 60 (Last element) print(data[-2]) # Output: 50 # Slicing syntax: [start:stop:step] print(data[1:4]) # Output: [20, 30, 40] print(data[::2]) # Output: [10, 30, 50] (Every 2nd item) print(data[::-1]) # Output: [60, 50, 40, 30, 20, 10] (Reversed copy)

3. List Manipulation Methods & Operations

Lists offer dedicated built-in methods for updating contents directly in memory.

fruits = ["apple", "banana"] # Appending and Extending fruits.append("cherry") # ['apple', 'banana', 'cherry'] fruits.extend(["date", "fig"]) # ['apple', 'banana', 'cherry', 'date', 'fig'] # Insertion and Removal fruits.insert(1, "mango") # Inserts 'mango' at index 1 popped_item = fruits.pop() # Removes and returns last item ('fig') fruits.remove("banana") # Removes first matching value 'banana' # Sorting and Reversing in-place numbers = [42, 11, 89, 23] numbers.sort() # In-place sort: [11, 23, 42, 89] numbers.reverse() # In-place reverse: [89, 42, 23, 11] print("Processed Fruits:", fruits) print("Sorted Numbers:", numbers)
In-Place Mutation Note: List methods like .sort(), .reverse(), and .append() modify the list in place and return None. Calling my_list = my_list.sort() will reset your variable to None!

4. Tuple Immutability & Structural Unpacking

Tuples protect reference integrity by preventing element alteration. They are widely used for returning multiple values from functions and structural unpacking.

# Single element tuple syntax requires a trailing comma single_item_tuple = (42,) # Tuple Unpacking coordinates = (37.7749, -122.4194, 15) latitude, longitude, altitude = coordinates print(f"Lat: {latitude}, Long: {longitude}") # Extended Unpacking with * (star operator) first, *middle, last = [1, 2, 3, 4, 5, 6] print("First:", first) # 1 print("Middle:", middle) # [2, 3, 4, 5] print("Last:", last) # 6
Memory Benchmark: Because tuples are immutable, Python optimizes memory space. Run import sys; sys.getsizeof([]) versus sys.getsizeof(()) to inspect base footprint overhead.

🏋️ Try It Yourself: Practice Challenges

Challenge 1: Duplicate Remover

Write a script that accepts a list with duplicate elements and returns a new list containing unique values while preserving their original order.

Challenge 2: Tuple Element Swapper

Given a pair stored in a tuple point = (x, y), write a function that swaps the positions of x and y using structural unpacking.

Challenge 3: List Chunking

Implement a function chunk_list(lst, size) that splits a given list into sub-lists of a specified size using sequence slicing.

⚡ Interactive Sandbox (Sequence Playground)
Console Output:
Click "Run Code" above to execute interactive sequence scripts...

📝 Knowledge Check Quiz

1. What is the return value of calling `my_list.sort()` in Python?
2. How do you create a single-element tuple in Python?
3. Why can a tuple be used as a dictionary key while a list cannot?
Advertisement
Horizontal Ad Banner Slot (728x90 / Responsive)