Python Lessons – 5.4 Tuples

Python Lessons - 5.4 Tuples


After the lists and dictionaries, another type of structured data that is widely used is the tuple. The tuple is very similar to a list, except that once defined this is immutable (ie the values contained within can not be changed). In Python, the tuple is recognizable because it is defined within round brackets ().

tuplename = (value1, value2, … )

The tuple values can be obtained by defining the position index in the same way as in the lists.


If you try to change a value of a tuple element, you get a TypeError exception.

tuple = (2,4,8)
tuple[0] = 4

if you run it, you get:

Traceback (most recent call last):
File "C:/Python34/", line 3, in <module>
tupla[0] = 4
TypeError: 'tuple' object does not support item assignment

An empty tuple can be defined this way

tuple = ()

Tuples such as lists agree to be nested, ie it is possible to define them as an element in another list. To derive then the innermost element, the indexing becomes double.

tuple = (1, (1,2,3), 2)

if you run it, you get

(1, 2, 3)

⇐ Go to Python Lesson 5.3 – Functions on dictionaries

Go to Python Lesson 5.5 – List slicing ⇒

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.