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 = ("192.168.1.1","192.168.1.2","192.168.1.3")

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]
'192.168.1.2'

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

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

>>> router_ip_addresses = ("192.168.1.1","192.168.1.2","192.168.1.3","192.168.1.4")

Now the tuple looks like this:

>>> router_ip_addresses
('192.168.1.1', '192.168.1.2', '192.168.1.3', '192.168.1.4')

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