AI summary by TwinMind
Lecture 10: Lists and Mutability
MIT OpenCourseWare
1h 15m 13s
Review of Previous Lecture
- Lecture 10 continuation from previous introduction of tuples and lists
- Tuples: immutable, straightforward operations similar to strings
- Lists: similar to tuples/strings but with key difference - mutability
- Focus today: mutability concept and syntax for compound data types
Basic List Operations Review
- Creating empty lists:
[] - Creating populated lists:
[2, 'hi', 4, [1, 3]](mixed data types allowed) - Standard operations: length, indexing, slicing, concatenation, max, iteration
- New capability:
L[3] = 10- direct element modification via indexing- Goes into memory and changes element at index 3
- Different from strings/tuples which don't allow this
Memory Diagrams - Mutation vs New Objects
- List mutation:
L[1] = 5changes existing object in memory- Original object modified, no new copy created
- Tuple reassignment:
T = (2, 5, 3)creates new object- Original tuple remains unchanged in memory
- Name
Trebound to new object
List Append Operation
- Syntax:
L.append(element) - Mutates original list by adding element to end
- Function used for side effect - returns
None - Common mistake:
L = L.append(5)- Results in
Lbeing assignedNone - Correct usage:
L.append(5)on separate line
- Results in
Dot Notation Explanation
- Format:
object.operation(parameters) - Object before dot: thing being operated on
- Operation after dot: function to perform
- Everything in Python is object with associated data and behaviors
- Different object types have different available operations
Coding Exercise - Make Ordered List
- Function:
make_ordered_list(n) - Creates list containing integers 0 through n (inclusive)
- Implementation:
- Create empty list
- Loop through
range(n+1) - Append each index to list
- Return completed list
Coding Exercise - Remove Elements
- Function:
remove_elem(L, e) - Creates new list excluding elements equal to
e - Implementation:
- Create empty new list
- Iterate through original list
- Add elements to new list if not equal to
e - Return new list
String-List Conversions
- String to list:
list(s)- each character becomes separate element - Split operation:
s.split(' ')- splits on specified character- More useful than character-by-character conversion
- Creates list of "words" when splitting on spaces
- List to string:
''.join(L)or'_'.join(L)- Character before dot specifies separator
- Only works with lists containing string elements
- Non-string elements must be cast to strings first
Word Counting Exercise
- Function:
count_words(sen) - Split sentence on spaces, return length of resulting list
- Two-line implementation: split then return length
- Demonstrates power of lists for text processing
Additional List Mutation Operations
- Sort:
L.sort()- mutates list to sorted order, returnsNone - Reverse:
L.reverse()- mutates list to reverse order, returnsNone - Sorted:
sorted(L)- returns new sorted list, original unchanged - Memory trick: "sort" = command (mutate), "sorted" = request (new copy)
Memory Diagrams - Sort vs Sorted
L.sort(): changes object in memory, same ID maintainedsorted(L): creates new object, original remains unchanged- Assignment patterns:
A = sorted(L)- correct, saves new sorted listB = L.sort()- incorrect, savesNone
Side Effects and Return Values
- Mutation functions (append, sort, reverse) used for side effects
- Return
Nonebecause job completed through mutation - Don't assign return values to variables
- Functions like
sorted()return new objects, must be assigned
Writing Custom Mutation Functions
- Example:
square_list(L)- squares each element in place - Must iterate over indices:
for i in range(len(L)) - Use
L[i] = L[i] ** 2syntax for element modification - Function returns
None(side effect only) - Calling pattern: just
square_list(my_list), no assignment
Three Tricky Loop Examples
Tricky Example 1: Range with Append
- Code:
for i in range(len(L)): L.append(i) - Behavior: Terminates normally
- Range creates fixed sequence at start: (0, 1, 2, 3)
- Each iteration appends index to list
- Original list: [1, 2, 3, 4] → Final: [1, 2, 3, 4, 0, 1, 2, 3]
Tricky Example 2: Direct Iteration with Append
- Code:
for e in L: L.append(i); i += 1 - Behavior: Infinite loop
- No predefined sequence - iterates over changing object
- As elements added, loop continues to process new elements
- Always four elements behind end of growing list
Tricky Example 3: Concatenation in Loop
- Code:
for e in L: L = L + L - Behavior: Terminates after 4 iterations
- Each iteration creates new object via concatenation
- Name
Lrebound to new object each time - Loop variable
estill references original object elements - Demonstrates difference between object names and objects themselves
Additional Operations
- Extend:
L1.extend(L2)- adds all elements of L2 to end of L1 - Clear:
L.clear()- removes all elements, keeps same object - ID function:
id(L)- returns memory location identifier- Same ID = same object (even after mutations)
- Different ID = different objects
Mutation vs Reassignment
L.clear()- mutates existing object (same ID)L = []- creates new empty list object (different ID)- Important distinction for understanding object identity
Summary
- Tuples: immutable, good for unchanging data (coordinates, page references)
- Lists: mutable, good for dynamic data (employee lists, shopping lists)
- Mutation operations modify existing objects in memory
- Side effect functions return
None - Understanding object identity crucial for debugging
