Previous Lesson | Table of Contents | Next Lesson |
When we make a list, we sometimes create it with the knowledge that we are not
going to modify it again. For example, if we create a list of the numbers from 1
to 10
, that list is not going to change unless our number system is overhauled. :)
From a Python perspective, in that case, instead of using a list
, we can use
a tuple
instead. Tuples are similar to lists, except that they are immutable,
meaning that they don’t have methods like append
or remove
. This property
makes them less resource-intensive (more memory efficient) to handle than lists.
Creating a tuple
is just like creating a list, except you replace brackets
with parentheses:
t = (1, 2, 3)
One minor detail is that if you are creating a tuple
with only one element,
you still need a comma at the end so that Python properly interprets that you
want to create a tuple:
s = (1,)
Indexing for tuples is exactly the same as with lists:
t = (1, 2, 3, 4, 5)
print(t[3])
This will output:
4
Let’s practice what we have learned with tuples:
Create a
tuple
with the following elements:23
,"dog"
, and5
. (solution)With your newly-created
tuple
, how would you print the3rd
element? (solution)
If you’re comfortable with tuple
, you can move on to discussing set
in the next lesson!