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] = 5 changes 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 T rebound 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 L being assigned None
    • Correct usage: L.append(5) on separate line

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, returns None
  • Reverse: L.reverse() - mutates list to reverse order, returns None
  • 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 maintained
  • sorted(L): creates new object, original remains unchanged
  • Assignment patterns:
    • A = sorted(L) - correct, saves new sorted list
    • B = L.sort() - incorrect, saves None

Side Effects and Return Values

  • Mutation functions (append, sort, reverse) used for side effects
  • Return None because 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] ** 2 syntax 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 L rebound to new object each time
  • Loop variable e still 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

TwinMind

Get summaries like this for your own meetings

TwinMind takes notes in the background during meetings, lectures, and calls, then writes the summary for you.

Free plan to get started

No bot joins your calls

Phone, desktop & Chrome apps

Your next meeting, summarized like this

TwinMind listens in the background and turns meetings, lectures, and calls into searchable notes you can chat with. Start free.

Available on phone, desktop & Chrome

Your next meeting, summarized like this

TwinMind listens in the background and turns meetings, lectures, and calls into searchable notes you can chat with. Start free.

Available on phone, desktop & Chrome

Your next meeting, summarized like this

TwinMind listens in the background and turns meetings, lectures, and calls into searchable notes you can chat with. Start free.

Available on phone, desktop & Chrome