Understand Tuples
In this step, you will learn about tuples in Python. Tuples are a fundamental data structure, similar to lists, but with a key difference: they are immutable. This means that once a tuple is created, its elements cannot be changed. This immutability makes tuples useful for representing fixed collections of items.
Let's start by creating a simple tuple:
my_tuple = (1, 2, 3)
print(my_tuple)
Create a file named tuple_example.py
in your ~/project
directory using the VS Code editor. Copy and paste the above code into the file.
Now, run the script using the following command in the terminal:
python tuple_example.py
You should see the following output:
(1, 2, 3)
Tuples are defined using parentheses ()
and elements are separated by commas.
Now, let's try accessing elements of the tuple:
my_tuple = (1, 2, 3)
print(my_tuple[0])
print(my_tuple[1])
print(my_tuple[2])
Add these lines to your tuple_example.py
file and run it again:
python tuple_example.py
You should see the following output:
(1, 2, 3)
1
2
3
You can access elements of a tuple using their index, just like with lists. Remember that indexing starts at 0.
Now, let's try to modify a tuple:
my_tuple = (1, 2, 3)
my_tuple[0] = 4 ## This will cause an error
Add this line to your tuple_example.py
file. When you run the script, you will encounter a TypeError
:
python tuple_example.py
Traceback (most recent call last):
File "/home/labex/project/tuple_example.py", line 2, in <module>
my_tuple[0] = 4
TypeError: 'tuple' object does not support item assignment
This error message confirms that tuples are immutable. You cannot change their elements after they are created.
Tuples can also contain different data types:
my_tuple = (1, "hello", 3.14)
print(my_tuple)
Modify your tuple_example.py
file to include this and run it:
python tuple_example.py
You should see the following output:
(1, 'hello', 3.14)
Tuples are a versatile data structure in Python, often used when you need to ensure that data remains constant throughout your program.