Tuples

The(20, 10) is a tuple. A tuple is a data structure in Python that is quite similar to a list but with some key differences. One common way to encounter a tuple is when a function returns multiple values.

For instance, consider this function that returns both the sum and the difference of two numbers:

def sum_and_difference (a, b):
    a_sum = a + b
    difference = a - b
    return a_sum, difference
    # We switched the order of return values

sum_diff = sum_and_difference(15, 5)
print(type(sum_diff))
Output
<class 'tuple'>

The function type() confirms that what's returned is a tuple.

Just like a list, we usually use a tuple to store multiple values. To create a tuple, we use parentheses to enclose the elements, separated by commas. Here's how we create and verify the type of a tuple:

a_list = [1, 'a', 10.5]
a_tuple = (1, 'a', 10.5)

print(a_tuple)
print(type(a_tuple))
Output
(1, 'a', 10.5)
<class 'tuple'>

Tuples support both positive and negative indexing, just like lists:

Tuples are immutable, meaning that their elements cannot be altered once they are created:

If we want to return a list instead of a tuple, we need to use brackets:

When we work with tuples, we can assign their individual elements to separate variables in a single line of code.

We can do the same with lists — we can assign individual list elements to separate variables in a single line of code:

We can use this variable assignment technique with functions that return multiple variables.

Convert Dictionary Values to Tuples

It is very difficult to sort dictionaries. So, we can use list of tuples.

Last updated