Tuples in Python

Tuples are one of the core object types in Python. Although tuples may seem like lists, they are often used in different situations and for different purposes and unlike lists they are immutable.

Syntactically they are enclosed in parenthesis (or without them) instead of square brackets like lists, but they support arbitrary types and the usual operations available with lists.

>>> tuple = (123, 'Hello World!', 21.03, 'AAA')
>>> tuple
(123, 'Hello World!', 21.03, 'AAA')
>>> len(tuple)
>>> tuple + ('BBB', 'CCC')
(123, 'Hello World!', 21.03, 'AAA', 'BBB', 'CCC')
>>> tuple
(123, 'Hello World!', 21.03, 'AAA')
>>> tuple[0]
>>> tuple[1]
'Hello World!'
>>> tuple[0] = 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

If you look at the last line above you can see that changing of a tuple value is not permitted as tuples are immutable. That is the main difference between tuples and lists in Python.

The reason to use tuples is to provide a integrity in large programs where you want to make sure that some data structures are not changed accidentally in the program. If you want to design a data structure and do not want to accidentally change the original data, tuples are what you should use.

One thought on “Tuples in Python

Leave a Reply

Your email address will not be published. Required fields are marked *