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]
wherem
is a list or tuple, andi
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()
, andmax()
behave the same for lists and tuples. - For
sum()
to workm
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()
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 m
returns 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 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)
wherei
is a valid index intom
pops the element at indexi
from the list.- We cannot pop from an empty list (IndexError).
m.index(x)
will return the index of the first occurrence ofx
inm
. Note: This will raiseValueError
ifx
is not inm
.
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.