Lesson 6
Dealing with Sequences of Objects
Chapter 7: Tuples
Accessing tuple elements
You can access elements in a tuple
just like in a list
:
>>> x = (1, 2, 3, 4, 5)
>>> print(x[0])
1
>>> print(x[1:3])
(2, 3)
>>> print(x[-1])
5
>>> print(x[:4:2])
(1, 3)
>>> print(x[::-1])
(5, 4, 3, 2, 1)
… but you cannot modify the elements. Try to understand the error messages produced by Python (we will discuss the attribute ‘append’ in the next lesson).
>>> x[1] = 6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> x.append(6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
If you need a new tuple, then create a new tuple! (But perhaps you should have just used a list
instead?)
>>> x = (1, 2, 3)
>>> print(x)
(1, 2, 3)
>>> x = (1, 2, 3, 4)
>>> print(x)
(1, 2, 3, 4)
Operators
You can use the +
, *
, and in
operators in the same way as list
s.
>>> print((1, 2) + (3, 4))
(1, 2, 3, 4)
>>> print((1, 2) * 3)
(1, 2, 1, 2, 1, 2)
>>> print(1 in (1,2))
True
>>> print(1 not in (1,2))
False