Datastructures - Tuples
Tuples are very similar to lists. The major difference is that they are
immutable. This means, after it has been created, we cannot add or remove
elements from it. It looks similar to a list, with the exception of
parenthesis instead of square brackets. They can also be created with the
built-in function tuple
. Slicing is still the same as well.
A tuple is an immutable ordered collection of elements, with its index starting at 0.
- tup01: is a tuple with five elements, some numerical and some strings.
- tup02: is a tuple with one element, note how we still need to include the comma.
- tup03: is a tuple with two elements.
We can even make an array of tuples, or a tuple of array's.
Same as a list, we can access the elements in a
tuple using its indices. For example,
x02[2][0]
corresponds to the first item of the third item
in the tuple x02, in this case the third item is a list, and
it's first item is the number 2.
While it's perfectly legal to mix how deep the elements in tuples or lists go, it's better to not, it's recommended to keep them consistent. For instance, in the following code editor, x01 has a doubly nested tuple as its second element. In contrast, every element in x02 is a tuple. It's preferable to use the x02 style over the x01 style.
x01 = [(3,5,7), ((9)), 11]
x02 = [(3,5,7), (9), (11)]
What is the motivation for tuples when we already learned lists? Tuples offer two benefits: they can't be changed, which is great when we don't want items reassigned, and they're slightly faster in terms of performance. Having said that, lists are the more common data structure and we will use it more in the course, however, there will be use cases for tuples.
That's all for tuples for now, another similar data structure called a set is next.