Python Tutorial Part 5 | Data Structures: Tuples

As we approach the conclusion of Python data structures, we’ll examine the tuple. Used less frequently than lists and dictionaries, tuples do serve some handy use cases where immutability is a critical requirement.

The final data structure to cover in this tutorial is called the ‘tuple’. In math terms, a tuple is an ordered arrangement of values. In programming, these may be numerals, but it can also be useful to create arrangements of text strung, or even other data structures.
A tuple is more similar to a list than to a dictionary in Python. However, the critical difference is that tuples are immutable. They are an ordered sequence of objects separated by commas and enclosed in parentheses (). Tuples are more limited than lists in functionality, but the immutability, or inability to change objects, within a tuple is the key advantage.

Why is Immutability Important?

Before diving further in how to work with tuples, why is immutability important? Take an example of a PID control block throttling a valve to control the flow rate of gas in a line. In this example, once the Kp, Ki, and Kd are tuned to control the gas flow rate they should not be changed.
Some industries are heavily regulated, including medical, pharma, or food & bev. But in various other, less highly regulated applications, parameters have a tendency to drift in production during “troubleshooting” steps taken by well-intentioned technicians or operators.
In the following gas line scenario, manipulation of the PID tuning may be disastrous and compromise the safety of personnel and plant assets. In this theoretical example, you would use a tuple to maintain the tuning integrity of the controller in the fast-paced automation environment.
PID flow control example

Figure 1. PID control of valve controlling gas flow rate in a pipe.

Using a Tuple Literal

To construct the tuple for the process in Figure 1, we will first use a tuple literal. This is straightforward, we will create parentheses and define each of the Kp, Ki, and Kd parameters within the parentheses For more info about these parameters and PID loops in general, check out this article, then pick back up right here.
We can also create the list in a more readable format with the constant values clearly defined:
Like lists, we can access elements using a numeric zero-based offset:
What happens now if we try to reassign the Kp to a value of 1.7?
The TypeError reinforces that the tuple data structure does not support changes after initial creation. As such, the useful methods we saw for dictionaries and lists do not exist for tuples. While this might seem to provide some lack of flexibility, this is the (obvious) tradeoff that results from insulating data from changes in the tuple structure.

Using Tuple Packing

Tuple packing is very similar to the prior tuple literal above. All this means is that a tuple can be defined without the use of parentheses:

Using the .tuple() Class Constructor

A slightly fancier mode of creating this pid_controller tuple is by using the .tuple() class constructor. Do not worry if the jargon class constructor is unfamiliar at this time, as this will be covered in later object-oriented programming articles in this series. The class constructor allows us to convert existing iterable data structures into a tuple. Iterable data structures can be acted upon in a loop, another concept we will cover in the future. For now, just understand that strings, lists, and dictionaries can be converted.
For example, a dictionary would be useful (aside from mutability) in representing the PID tuning parameters to key value pairs. Converting the data structure would appear below:
Notice that we called the .items() method associated with the pid_controller dictionary instance. This example highlights how the basic core concepts of Python are all intertwined in practice. To highlight what happened here:

  • The .items() method returned all key-value pairs of the pid_controller dictionary as tuple data types. For example, (‘Kp’: 1.4).
  • The tuple constructor, which returns a tuple from the pid_controller, was able to store the tuples returned from the .items() method; tuples can be nested within a tuple.

Mutable Objects Within a Tuple

While on the subject of tuple immutability, there is an important caveat to make. Tuples may contain mixed data types like lists and dictionaries. Therefore, although tuples themselves are immutable, objects nested within them can still be modified. Let’s attempt to change the nested list item that we have called ‘ERROR’ below:
Even though tuples are immutable, a mutable change to the nested list was allowed.

Tuple Unpacking

The packing of tuples can be easily reversed by using tuple unpacking.
The tuple is unpacked into 3 individual variables Kp, Ki, and Kd.

Concatenating Tuples

Tuples can also be concatenated together by using the + operand.

Tuple Methods: .count() and .index()

Tuples offer fewer features than lists and dictionaries, so the only two methods that exist for the data structure are .count() and .index().
The .count() method finds the number of times an object is within a given tuple:
The .index() method returns the offset number of the first instance of an object if present in the tuple:

Wrapping Up Python Data Structures

We’ve traversed data structures in order of usefulness. The next section (forthcoming) in this series will cover sets as our last step in closing the page on data structures.


Copyright Statement: The content of this website is intended for personal learning purposes only. If it infringes upon your copyright, please contact us for removal. Email: [email protected]

Leave a Comment