Python Tuples

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 add strings to a tuple:

>>> router_ip_addresses = ("","","")

You can also add numbers to a tuple:

my_numbers = (1,2,3,4,5,6)

Similar to how a list works, we can access items in the tuple. For example:

>>> router_ip_addresses[1]

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:

>>> router_ip_addresses.append("")
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in 
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:

>>> router_ip_addresses.pop(0)
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in 
AttributeError: 'tuple' object has no attribute 'pop'

The tuple doesn’t have a pop attribute to remove items.

Lists vs Tuples

Why would you want to use a tuple instead of a list?

To be honest, for us network engineers it doesn’t matter much. You could use a tuple to “write protect” your data but on the other hand, you can still overwrite the tuple if you want. Let me show you what I mean.

This is what our “router_ip_addresses” variable looks like now:

>>> router_ip_addresses
('', '', '')

It’s a tuple with three items. Let me reassign the “router_ip_addresses” variable with a new tuple:

>>> router_ip_addresses = ("","","","")

Now the tuple looks like this:

>>> router_ip_addresses
('', '', '', '')

I reassigned the “router_ip_addresses” variable with a new tuple, which is no problem in Python.

When you have huge data sets, apparently a tuple is faster 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 because you have to process so much data.

Ask a question or start a discussion by visiting our Community Forum