Tuples#

Tuples, similar to lists, provide a means to collect and organize data. However, what sets tuples apart is their immutability - once created, the elements within a tuple cannot be modified. In this guide, we’ll delve into what tuples are, explore why they are used, and demonstrate some practical use cases for these unchangeable data structures.

Understanding Tuples#

A tuple is a collection of elements, just like a list, but it differs in a crucial way: it cannot be changed or altered once it is declared. This immutability makes tuples an ideal choice for situations where you want to ensure that the data remains constant throughout your program’s execution. Think of tuples as containers for values that should remain fixed, such as the results obtained from a database SELECT statement in SQL. These results might be crucial to your Python program, but you want to guarantee their integrity and prevent any unintentional modifications.

Creating Tuples#

Creating a tuple in Python is quite straightforward. Instead of using square brackets, as you would with a list, you use parentheses to define a tuple. Here’s how you can create tuples to store server names and ages:

servers = ('web01', 'web02', 'app01', 'db01')
ages = (12, 19, 32, 41)

Once you’ve created these tuples, you can access their elements using indexing, just like you would with a list. For example, to retrieve the first element from the ages tuple, you can use:

print(ages[0])
12

Use Cases for Tuples#

Now, let’s explore some practical use cases for tuples:

  • Storing Constants: Tuples can be used to store constant values, such as mathematical constants or configuration settings, ensuring that they remain unchanged throughout the program’s execution.

  • Multiple Return Values: Functions in Python can return multiple values as a tuple. This allows you to efficiently pack and unpack data when calling and receiving function results.

def get_user_info(user_id):
    # ... retrieve user data ...
    return ('John', 'Doe', 30)

first_name, last_name, age = get_user_info(123)
  • Database Results: As mentioned earlier, tuples are perfect for holding database query results. They maintain the integrity of fetched data while allowing you to work with it effectively.

  • Coordinate Pairs: Tuples can be used to represent coordinates or pairs of values, which is handy in applications involving geometry or mapping.

lat = 43.642567
long = -79.387054
cn_tower = (lat, long) # immutable
print(f"The CN Tower stands at {cn_tower[0]} latitude, and {cn_tower[1]} longitude.")
The CN Tower stands at 43.642567 latitude, and -79.387054 longitude.

Note

Tuples can be sliced, see Slicing for more details.