In this article, we are going to talk about Tuples. A Tuple is a collection of objects (elements).
Well, does this definition remind you with something?! Right!! It is the same definition we used when we introduced Lists. In fact, tuples and lists are very similar; both are collections of comma-separated objects, both are accessible via zero-based index, and both allow operations like slicing. While lists are enclosed within square brackets, tuples – on the other hand – use parentheses. But the main difference between the two very-similar structures is that tuples are immutable, while lists are not. Remember when we talked about Strings; they were also immutable. Immutable means that they can’t be changed, or updated. So, tuples could be considered as read-only lists.
Declaring and Initializing Tuples
Like other Python structures, Tuples are declared and initialized in the step. For example:
This declares and initializes a tuple whose name is digits which contains the numbers from 0 to 9.
Similarly, the following initialization statements:
Accessing an Individual Element in a Tuple
The same way used to access individual array elements also applies here. To read the second element of the countries tuple, use the following statement:
To extract a portion of a tuple based on a range of indexes.
Are they Really Immutable?!
I claimed that tuples are immutable, could you prove the opposite?!
The Python interpreter generated an error when trying to update the value of an element in a tuple. It says clearly that tuples don’t support item assignment. Do you believe me now?!
Tuples Functions and Methods
Tuples have a number of useful functions and methods. In this section, we are going to investigate those methods with illustrative examples.
The len function returns the length (number of elements) of a tuple.
min and max Functions
The min and max functions return the minimum and maximum values in a tuple, respectively.
The tuple function converts an array into a tuple.
The index Method
The index method searches a tuple (or part of it) for a specific value, and if found it returns the index of the element that matches the value.
The count Method
The count method also searches a tuple for a value, but instead of returning the index, it returns the number of occurrences (matches) for this value.
* * * * * *
In this article, we have talked about tuples. Tuples are very similar to arrays in many things, they are initialized the same way, their elements are accessed also the same way, and even the same functions and method applies to both like len, min, max, index, and count. Two main differences distinguish tuples from lists: the first is the use of parentheses instead of square brackets, and the second is that tuples are read-only (immutable).
See you in the next article.