HomePython Page 3 - Data Structures in Python: Lists and Tuples
Tuple - Python
Different languages use different kinds of data structures to handle the way data is arranged in memory. This article looks at two of the more common data structures used by Python.
According to its definition, "A tuple is a finite sequence (also known as an "ordered list") of objects, each of a specified type." In other words, a tuple is an ordered collection of objects of different types. In Python, a tuple is a list of comma-separated values but immutable, unlike a list. So the operations on a tuple are restricted to the ones that don't affect its immutability. Accordingly, the following are the operations that can be performed on a tuple:
Creation
Accessing
Due to a tuple's immutability, deletion and addition of new elements are not possible.
Creation: Creating or defining a tuple is as simple as giving a list of values within parenthesis. For example
>>> tup = (2, 4, 6, 8, 10)
is a tuple. If a tuple has only one element, it would be defined as follows:
>>> tup = (5,)
Accessing: Since lists and tuples are almost the same, the accessing mechanisms also work in a similar fashion. Elements of a tuple can be accessed in two ways:
Index based: The elements of a tuple can be accessed using their indices. The index starts at 0. For example, to access an element at index 0 of a tuple tup, the statement would be:
Slicing: As with a list, slice operator can be used to access elements of a tuple. It selects a range of elements. For example the following statement selects elements between 1 and 3 (excluding 3):
>>> tup[1:3] ('b', 'c')
That covers operations on a tuple. So the question arises, when do you use a list and when do you use a tuple? A list can be used in almost all cases. However, there are certain contexts where a tuple is more useful. These are:
When you need speed. Tuples are faster than lists. If you're defining a constant set of values and all you're ever going to do with it is iterate through it, use a tuple instead of a list.
When your data will not change. It makes your code safer if you "write-protect" data that does not need to be changed. Using a tuple instead of a list is like having an implied assert statement that this data is constant, and that special thought (and a specific function) is required to override that.
In all other contexts, lists can be used. That brings us to the next section, which is a real world example using a list.