Python Lessons – 5.4 Tuples

Python Lessons - 5.4 Tuples

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.

tuplename[1]

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

if you run it, you get:

An empty tuple can be defined this way

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.

if you run it, you get

⇐ 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.