Quarry School

Update an item by index — quick review

In plain words

A whiteboard of scores can be wiped and rewritten, one cell at a time, and a new row can be added at the bottom.

Rule

A list is mutable. a[i] = v replaces the item at index i with v and keeps the length; a.append(v) adds v at the end and makes the list one item longer. A string is immutable: assigning to one of its characters raises a TypeError.

Step

  1. Write the list with each index under its item.

  2. Before name[i] = value, check that index i names an item: for a list of n items, from 0 up to n - 1, or from -1 back to -n counting from the end.

  3. For name[i] = value, cross out the item at index i and write the new value there.

  4. For name.append(value), write the value after the last item and add 1 to the length.

  5. Print the list to see its items after the changes, and print len() of it to see how many items it holds.

Trap

Assigning the result of append to the list's name loses that name for the list. append changes the list and gives back None, so after scores = scores.append(10) the list has grown, but scores names None.

To add an item, use append, not an index one past the end: scores[3] = 10 on a list of three items stops with an IndexError.