tuple
data type
in the
Python
Standard Library
collections.namedtuple
in the
Python
Standard Library
We saw in
List of numbers
that a
list
is a
mutable
sequence.
a = [10, 20, 30] a[1] = 25 #Overwrite the 20. for i in a: print(i)
10 25 30
We saw in
Indexing
that a
string
is an
immutable
sequence.
s = "abc" s[1] = "B" #Try to overwrite the lowercase "b". print(s)
Traceback (most recent call last):
File "/Users/myname/python/index.py", line 2, in <module>
s[1] = "B"
TypeError: 'str' object does not support item assignment
The workaround is
s = "abc" s = s[:1] + "B" + s[2:] #Paste together a new s. print(s)
aBc
The word
tuple
is a generalization of the words
double, triple, quadruple, quintuple, sextuple, septuple, octuple, nonuple,
etc.
Create the tuple with
(parentheses)
and commas.
t = (10, 20, 30)
t[1] = 25
for i in t:
print(i)
Traceback (most recent call last):
File "/Users/myname/python/index.py", line 2, in <module>
t[1] = 25
TypeError: 'tuple' object does not support item assignment
If you don’t need to change the values in a
list,
and don’t need to insert or delete items,
use a
tuple
instead of a
list.
A
sequence
that is immutable (e.g., a
tuple)
requires less space and time than a sequence that is mutable (e.g., a
list).
Clothes makes the man,
and commas make the tuple
(unless the tuple is empty).
A tuple is created by one or more
comma
operators
that are not enclosed within
[square
brackets].
For example,
the commas in
h
and
i
are all you need to make a tuple,
but it’s clearer to write the parentheses too.
On the other hand,
g
is an
int
for the same reason that
j
is an
int.
The parentheses in the
g
line do nothing.
a = [10, 20, 30] #a is a list of 3 ints b = [10, 20] #b is a list of 2 ints c = [10] #c is a list of 1 int d = [] #d is a list of 0 ints e = (10, 20, 30) #e is a tuple of 3 ints f = (10, 20) #f is a tuple of 2 ints g = (10) #g is an int, not a tuple. The parentheses do nothing. h = (10,) #h is a tuple of 1 int i = 10, #i is a tuple of 1 int j = 10 #j is an int k = () #k is a tuple of 0 ints
(a, b, c) = (10, 20, 30) #a, b, c are 3 ints. Parentheses optional on both sides. t = (10, 20, 30) #t is a tuple containing 3 ints. Parentheses optional.
lists
to
tuples
in
Roman,
Plot Generator,
and
Manhattan.
Simply change the
[square
brackets]
to
(parentheses)
in the statements that create the
lists.
If a resulting
tuple
contains exactly one item,
you will also have to add a comma.
dictionaries
and
sets,
you’ll see another reason to use
tuples.
The keys of a
dictionary
and
set
must be immutable,
which means that key cannot be a
list.
But a key could be a
tuple.
See
Sparse.
collections.namedtuple.