List and tuple reference
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]wheremis a list or tuple, andiis 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(), andmax()behave the same for lists and tuples. - Python built-in
sorted()returns a sorted list of elements in a given sequence. - For
sum()to workmmust contain only numeric types (int,float) or Booleans. So, for example,sum([1, 1.0, True])yields three. We cannot sum over strings. min()andmax()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 mreturns a Boolean. m.sort(),m.append(), andm.pop()work for lists only. Tuples are immutable. Note that these change the list in place.- We cannot apply
m.sort()if the list contains elements which are not comparable. By the same token,sorted()will will not work if elements in the sequence 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)whereiis a valid index intompops the element at indexifrom the list.- We cannot pop from an empty list (IndexError).
m.index(x)will return the index of the first occurrence ofxinm. Note: This will raiseValueErrorifxis not inm..replace()returns a copy of a string, replacing occurrences of one substring with another..join()takes some glue—a string—and uses this to connect elements in some sequence..split()returns a list of elements resulting from splitting the string. Whitespace is the default delimiter, but any string can be supplied as an alternative.
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.