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:
We can access items in the tuple by specifying the index number in brackets  behind the tuple:
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:
It’s a tuple, not a list, so the append attribute doesn’t exist. You also can’t delete anything from the tuple:
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:
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.
When you have huge data sets, apparently a tuple is faster than a list. A tuple also requires less memory than a list. This is an issue that computer scientists might run into. As network engineers, we typically use Python for small scripts or to communicate with APIs. It’s unlikely that you run into any Python performance issues where the difference between a tuple or list is a key factor.
You have now learned what Python tuples are:
- Tuples are similar to lists, but you can’t modify them.
- It is possible to re-declare a variable that contains a tuple, though.
- Theoretically, tuples are faster than lists but it’s unlikely as a network engineer to run into a performance issue like this.