Python Tuples

Python Tuples

Explain tuple data type and use-cases in Python.

Here is a summary of tuples in Python: Tuples are immutable ordered sequences of objects in Python. Once a tuple is created, you cannot change its elements.

Syntax:

A tuple is created by placing all the items (elements) inside parentheses ( ), separated by commas.

tup1 = (1, 2, 3)  
tup2 = ("a", "b", "c")

Elements:

We can access elements of a tuple using the square bracket notation with the index of the element we want to access.

tup1 = (1, 2, 3)
print(tup1[0]) # Prints 1
print(tup1[2]) # Prints 3

Use-cases:

  • Since tuples are immutable, we use them whenever we want to create a sequence of elements that should not change.

  • Tuples are often used as keys in dictionaries since dictionaries require immutable keys.

  • We can use tuples to return multiple values from a function.

  • Tuples take less memory than lists since tuple values are immutable.


Decomposition

Tuple deconstruction in Python allows you to assign multiple variables in one line using tuples. It's a useful way to unpack tuples.

For example:

coord = (3, 5)

# Tuple deconstruction 
x, y = coord  

print(x) # Prints 3
print(y) # Prints 5

Here we have a tuple coord with two elements. Using tuple deconstruction, we assign the first element to x and the second element to y in one line.

You can also assign part of a tuple to variables:

coord = (3, 5, 7, 9)

# Assign first two elements to x and y  
x, y = coord[0], coord[1]

print(x) # Prints 3  
print(y) # Prints 5

Here we assign only the first two elements of coord to x and y.

Tuple deconstruction is a handy feature in Python to unpack tuples in a concise way. It makes code more readable compared to accessing individual elements of a tuple and assigning them.


Rest Operator

The rest operator (*) used with tuple deconstruction allows you to assign the remaining elements of a tuple to a variable.

For example:

coord = (3, 5, 7, 9)

# Assign first two elements to x and y  
# And rest to z
x, y, *z = coord  

print(x) # Prints 3  
print(y) # Prints 5
print(z) # Prints [7, 9]

Here we assign:

  • The first element of coord to x

  • The second element to y

  • And the rest (remaining) elements to z using the *z rest operator.

So z becomes a list containing the last two elements of coord.

This is useful when you want to assign:

  • The first few elements of a tuple to specific variables

  • And the rest of the elements to a single variable.

You can also use the rest operator in the middle:

coord = (3, 5, 7, 9)

x, *y, z = coord

print(x) # 3
print(y) # [5, 7] 
print(z) # 9

Here *y collects the middle elements, and z gets the last element.

So in summary, the rest operator (*) while tuple deconstructing allows you to collect the remaining elements of a tuple and assign them to a single variable.

Ignoring values

When deconstructing a tuple, you can ignore some of the values using an underscore _.

For example:

coord = (3, 5, 7, 9)

x, _, y, _ = coord

print(x) # 3
print(y) # 9

Here we ignore the second and fourth elements of the tuple by using _ in their place. This simply discards those values, we do not assign them to any variable.

This is useful when you want to:

  • Assign only some specific values from the tuple to variables

  • And ignore the rest of the values.

Instead of using _ to ignore values, you could also use an underscore variable name:

coord = (3, 5, 7, 9)

x, z, y, t = coord

print(x) # 3  
print(y) # 9

Here we use z and t as variable names, but we never use those variables. They simply ignore/discard the second and fourth values from the tuple.

So in summary, when decomposing tuples you can use _ or unused variable names to ignore specific values, while assigning the others to variables you actually need.

Hope this explanation of ignoring values during tuple decomposition was helpful! Let me know if you have any other doubts.


Multiple Results

You can use tuples to return multiple results from a function. This is done by returning a tuple from the function.

For example:

def add_subtract(x, y):
    add = x + y
    subtract = x - y 
    return (add, subtract)

result = add_subtract(3, 5)

print(result)
# (8, -2)

add, subtract = add_subtract(10, 5)

print(add) 
# 15

print(subtract)
# 5

Here the add_subtract() function:

  • Calculate the sum and difference between the two arguments

  • Returns both results as a tuple using return (add, subtract)

When we call the function, we either:

  • Store the entire tuple result in a variable result

  • Or we decompose the tuple and assign each result to a variable like add and subtract

So by returning a tuple, the function can "return" multiple result values, not just one.

The benefits of this approach are:

  • The function can calculate multiple related results

  • And return all of them in one call

  • The caller can then either use the entire tuple or decompose it as needed.

So in summary, by returning a tuple, a function can return multiple result values to the caller, instead of just one.


List of Tuples

A list of tuples in Python is a list where each element is a tuple.

For example:

list_of_tuples = [(1, 2), (3, 4), (5, 6)]

Here we have a list list_of_tuples containing 3 tuples:

  • (1, 2)

  • (3, 4)

  • (5, 6)

We can access individual tuples using indexes:

first = list_of_tuples[0]
print(first)
# (1, 2)

second = list_of_tuples[1]
print(second)  
# (3, 4)

And we can access individual tuple elements using double indexes:

first_element = list_of_tuples[0][0]
print(first_element)
# 1

second_element = list_of_tuples[1][1]
print(second_element)
# 4

Here list_of_tuples[0] accesses the first tuple, and [0] then accesses the first element of that tuple.

We can also iterate through the list of tuples:

for tuple in list_of_tuples:
    print(tuple)

# (1, 2)
# (3, 4) 
# (5, 6)

The main uses of a list of tuples are:

  • When you have a collection of related data points that fit well into tuples

  • And you want to store all those tuples in a list for easy access and iteration.

So in summary, a list of tuples allows you to store multiple tuples in a list, for easy access and iteration. Each tuple can contain related data, and the entire list of tuples then represents a collection of data.


Disclaim: I have created this article using Rix, and AI text and code generator. Hope is useful for you. Definitely is useful for me and other people who learn Python.