In this lesson, you’ll explore defining and using tuples. Tuples are identical to lists in all respets, except two. They are immutable and are defined by enclosing the elements in parentheses instead of square brackets:
a = ('spam', 'egg', 'bacon', 'tomato')
Here’s why you would choose to use a tuple instead of list:
- Program execution is faster when manipulating a tuple than it is for the equivalent list.
- You don’t want data modified.
- A Python dictionary requires keys that are of an immutable type.
Here’s an example:
>>> t = ('spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster')
>>> t
('spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster')
>>> type(t)
<class 'tuple'>
>>> t[0]
'spam'
>>> t[-1]
'lobster'
>>> t[3:6]
('tomato', 'ham', 'lobster')
>>> t[1:4]
('egg', 'bacon', 'tomato')
>>> t[0:6:2]
('spam', 'bacon', 'ham')
>>> t[::-1]
('lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam')
>>> t
('spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster')
>>> t[2]
'bacon'
>>> t[2] = 'butter'
Traceback (most recent call last):
File "<input>", line 1, in <module>
t[2] = 'butter'
TypeError: 'tuple' object does not support item assignment
>>> a = 'spam'
>>> b = 42
>>> a, 3.14159, b
('spam', 3.14159, 42)
>>> t = ()
>>> type(t)
<class 'tuple'>
>>> t
()
>>> t = (1, 2)
>>> type(t)
<class 'tuple'>
>>> t = (2)
>>> t
2
>>> type(t)
<class 'int'>
>>> t = (2, )
>>> type(t)
<class 'tuple'>
>>> t
(2,)
Pygator on Sept. 29, 2019
Never thought about singleton tuples, never tried to make such a tuple in all my years of python programming!