Lesson Contents
A tuple is like a list, but once created, you can’t edit it. A tuple is immutable. You create a tuple by adding items between parentheses ().
Here is an example where we create two tuples:
>>> hostnames = ("H1","SW1","R1","ASA1")
>>> my_numbers = (1,2,3,4,5)
We can access items in the tuple by specifying the index number in brackets [] behind the tuple:
>>> hostnames = ("H1","SW1","R1","ASA1")
>>> my_numbers = (1,2,3,4,5)
Will show this output:
>>> print(hostnames[2])
R1
>>> print(my_numbers[3])
4
Adding or removing items in a tuple
A tuple is immutable so you can’t modify it like a list. For example, try adding something to the tuple:
>>> hostnames = ("H1","SW1","R1","ASA1")
>>> hostnames.append("SW2")
Will show this output:
Traceback (most recent call last):
File "", line 1, in
hostnames.append("SW2")
^^^^^^^^^^^^^^^^
AttributeError: 'tuple' object has no attribute 'append'
It’s a tuple, not a list, so the append attribute doesn’t exist. You also can’t delete anything from the tuple:
>>> hostnames = ("H1","SW1","R1","ASA1")
>>> hostnames.pop(2)
Will show this output:
Traceback (most recent call last):
File "", line 1, in
hostnames.pop(2)
^^^^^^^^^^^^^
AttributeError: 'tuple' object has no attribute 'pop'
The tuple doesn’t have a pop attribute to remove items.
You could use a tuple to “write protect” the contents of the tuple since you can’t modify it. However, it is possible to re-declare a tuple. Here is an example:
>>> hostnames = ("H1","SW1","R1","ASA1")
>>> hostnames = ("H3","SW4","R8")
>>> print(hostnames)
Will show this output:
('H3', 'SW4', 'R8')
Above, I re-declared the variable “hostnames” with a new tuple. This is no problem in Python so the “write protect” analogy doesn’t make much sense.
Tuple vs List
Why would you want to use a tuple instead of a list?
To be honest, for us network engineers it doesn’t matter much.
Hi Rene,
What does it mean that You could use a tuple to “write protect” the contents of the tuple since you can’t modify it.
Hello Pradyumna
One of the characteristics of a tuple data type as opposed to a list is that it is immutable. This means that the value stored within the variable cannot be changed. For example, if you try to change a value within the tuple, it will return an error, as shown in the lesson.
Since the values stored within a tuple cannot be changed, we can say that they are “write protected” in much the same way as a write protected file cannot be changed. In other words, if you use a tuple in your programming, you can be sure that even an error in coding canno
... Continue reading in our forum