List and tuple reference

Published

2023-08-01

Sequences: a quick reference guide

Mutability and immutability

Type Mutable Indexed read Indexed write
list yes yes yes
tuple no yes no
str no yes no

Built-ins

Type len() sum() min() and max()
list yes yes (if numeric) yes, with some restrictions
tuple yes yes (if numeric) yes, with some restrictions
str yes no yes

Methods

Type .sort(), .append(), and .pop() .index()
list yes yes
tuple no yes
str no yes
  • If an object is mutable, then the object can be modified.
  • Indexed read: m[i] where m is a list or tuple, and i is a valid index into the list or tuple.
  • Indexed write: m[i] on left-hand side of assignment.
  • Python built-in len() works the same for lists and tuples.
  • Python built-ins sum(), min(), and max() behave the same for lists and tuples.
  • For sum() to work m must contain only numeric types (int, float) or Booleans. So, for example, sum([1, 1.0, True]) yields three. We cannot sum over strings.
  • min() and max() work so long as the elements of the list or tuple are comparable—meaning that >, >=, <, <=, == can be applied to any pair of list elements. We cannot compare numerics and strings, but we can compare numerics with numerics and strings with strings.
  • We can test whether a value is in a list or tuple with in. For example 'cheese' in m returns a Boolean.
  • m.sort(), m.append(), and m.pop() work for lists only. Tuples are immutable. Note that these change the list in place.
  • We cannot apply m.sort() if the list or tuple contains elements which are not comparable.
  • We must supply an argument to m.append() (we have to append something).
  • m.pop() without argument pops the last element from a list.
  • m.pop(i) where i is a valid index into m pops the element at index i from the list.
  • We cannot pop from an empty list (IndexError).
  • m.index(x) will return the index of the first occurrence of x in m. Note: This will raise ValueError if x is not in m.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).