Python Tuple

In Python, a tuple is a immutable sequence type. This means that once you create a tuple, you cannot change the values it contains: you cannot add, remove, or change the values of any of the elements in the tuple.

Tuples are defined using parentheses ( ) , with elements separated by commas. For example, you can create a tuple containing three elements like this:

>>> t = (1, 'a', 3.14)

You can access the elements of a tuple using indexing, just like you do with lists. The indexes start at 0 and go up to the number of elements in the tuple minus 1. For example, to access the second element of the tuple t in the example above, you would use the following syntax:

>>> t[1]
'a'

You can also use slicing to access a range of elements in a tuple. For example, to get the first two elements of the tuple t, you would do:

>>> t[0:2]
(1, 'a')

Tuples are often used to group related data together, and are particularly useful when you want to return multiple values from a function. For example, you might have a function that calculates the mean and standard deviation of a list of numbers, and you want to return both values to the caller. You could do this using a tuple:

def mean_and_stddev(values):
    mean = sum(values) / len(values)
    variance = sum((x - mean) ** 2 for x in values) / len(values)
    stddev = math.sqrt(variance)
    return mean, stddev

# Example usage
m, s = mean_and_stddev([1, 2, 3, 4])
print(f'Mean: {m}, Standard deviation: {s}')

This would print Mean: 2.5, Standard deviation: 1.118033988749895

Was this helpful?
[0]