PySchools Python Quick Reference Guide

Tuples

«  Dictionaries   ::   Contents   ::   Object Oriented Programming  »

Tuples

Tuple is very similar to a list, which contains a sequence of objects. Its main difference is it cannot be modified after creation. A tuple is created by assigning a list of comma-separated values to a variable. For clarity, it is recommended to enclose the values with the parentheses.

>>> t1 = ('a', 'b', 'c')                # create a tuple with values: 'a', 'b', 'c'
>>> type(t1)
<type 'tuple'>

>>> t2 = 1, 2, 3, 4, 5                  # create a tuple with values: 1, 2, 3, 4, 5
>>> t2
(1, 2, 3, 4, 5)

>>> t3 = ()                             # create an empty tuple

>>> t4 = (5,)                           # create a tuple with one element, need to add a comma

Accessing Values in Tuple

Like List and String, Tuple is zero indexed. The same slicing rule applies for accessing elements within a tuple. See examples below:

>>> x = ('a', 'b', 'c', 'd', 'e')
>>> x[0]                                # Getting first element
'a'
>>> x[-1]                               # Getting last element
'e'
>>> x[1:3]                              # Getting second and third elements using slicing
('b', 'c')

Modifying a Tuple

Tuple is immutable, and therefore its value cannot be modified directly. However, you can “modify” a tuple by re-assigning the value to another tuple.

>>> a = (1, 2, 3, 4, 5)
>>> a[0] = 10
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

>>> b = (10,) + a[1:]       # replace the first element with (10,), and reassign the result to a new tuple
>>> b
(10, 2, 3, 4, 5)

>>> del a[0]                # Not allowed to delete elements in a tuple
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion

>>> del a                   # You can delete the whole tuple

See also

Ready for some practice? Test your understanding at PySchools: Tuples.

«  Dictionaries   ::   Contents   ::   Object Oriented Programming  »