After seeing lists in the last chapter, in this one, we will learn about tuples.
Tuples are similar to lists. They are sequential structures used to store different kinds of data.
The big difference between them is that a tuple is immutable. You can’t redefine elements in a tuple, change its values or any similar operation.
Creating a tuple and accessing its elements
The way to create a tuple is similar to creating a list, except that for tuples we use parentheses, instead of square brackets. Like lists, we separate the items with commas.
tuple1 = ("Cat", "Dog", "Parrot", "Turtle") print(tuple1) > ("Cat", "Dog", "Parrot", "Turtle")
Accessing elements in a tuple is the same as with lists, using square brackets with the index where the item is located:
print(tuple1) > Parrot
slicing also works the same in tuples. You define the interval you want to slice on the tuple inside square brackets:
print(tuple1[1:3]) > ('Dog', 'Parrot')
And you can also create an empty tuple, with empty parentheses, without any element inside:
empty_tuple = () print(empty_tuple) > ()
Remember that we said that a tuple is imumtable. Let’s test this and try to change the value of an item inside a tuple:
tuple = "Elephant" > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: 'tuple' object does not support item assignment
Python itself raises an error. Typle does not support what Python calls item assignment.
Likewise, it’s not possible to remove items from a tuple. What yu can do is to create a new tuple without the item, or delete the tuple entirely with the
del(tuple1) print(tuple1) > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > NameError: name 'tuple1' is not defined
Most of the functions that we saw on the last chapter to use with lists, also work with tuples, like,
min(), for example:
tuple2 = (8.3, 9.4, 3.3, 7.5, 7.6) print(max(tuple2)) print(min(tuple2)) print(len(tuple2)) > 9.4 > 3.3 > 5
And it’s also possible to convert a list to a tuple, and vice-versa, using the functions
list1 = list(tuple1) print(list1) list2 = ["José", "Afonso", "Carlos", "Luiz"] tuple3 = tuple(list2) print(tuple3) > ["Gato", "Cachorro", "Papagaio", "Tartaruga"] > ('José', 'Afonso', 'Carlos', 'Luiz')
And with that, we conclude the chapter about tuples, which, to summarize, are immutable lists. We saw that a lot of what works with lists, also work with typles, and the ways to create and access data in a tuple. In the next chapter, we will talk about dictionaries, interesting structures to store data in a way that’s different than lists and tuples.