Tuples and Ranges
Python has a built-in tuple class tuple
is very
similar to a list
in that it
is an ordered collection of elements. The term “tuple” is a
generalization of the terms “single,” “double,” “triple,” “quadruple,”
and so on. The primary difference between a tuple and a list is that a
tuple is immutable, so its elements can’t be changed. The syntax for a
tuple literal of elements e
\(x\) is (e1, e2, ..., en)
. The elements can
each be of any type, including tuples. For example, the following
statements return tuples:
0, 1, 2, 4, 5)
("foo", "bar", "baz")
(0, 1], [2, 3])
([0, 1), (2, 3))
((0, "foo", [1, 2], (3, 4)) (
Elements of a tuple can be accessed via the same syntax as is used for lists, including slicing. For instance,
= (0, 1, 2)
t 1] # => 1
t[0:2] # => (0, 1)
t[1:] # => (1, 2) t[
Because tuples are immutable, there are only two built-in tuple
methods, count()
and index()
. The count()
method returns the number of
times its argument occurs in the tuple. For instance,
= (-7, 0, 7, -7, 0, 0)
t -7) # => 2 t.count(
The index()
method returns
the index of the first occurrence of its argument. For instance,
= ("foo", "bar", "baz", "foo", "bar", "baz", "baz")
t "baz") # => 2 t.index(
The range built-in type is a compact way
or representing sequences of integers. A range
can be
constructed with the range(start, stop, step)
constructor function, as in the following examples:
list(range(0, 3, 1)) # => [0, 1, 2]
list(range(2, 6, 1)) # => [2, 3, 4, 5]
list(range(0, 3)) # => [0, 1, 2] (step=1 by default)
list(range(3)) # => [0, 1, 2] (start=0 by default)
Note that we have wrapped the ranges in list()
functions, which converted each range to a list. This was only so we can
see the values it represents; alone, an expression like range(0, 3)
returns itself. This is why a range is such a compact data point—all
that needs to be stored in memory are the start
, stop
, and step
arguments because the intermediate
values are implicit.
Online Resources for Section 1.7
No online resources.