Tuples

·

3 min read

Tuples

Python tuples are a collection of objects, which are ordered and immutable. Tuples are very similar to lists in Python, but with one key difference - once a tuple is created, it cannot be changed. This means that you cannot add or remove elements from a tuple.

Creating Tuples

In Python, we can create a tuple by enclosing a sequence of values in parentheses.

Example:

# Creating a tuple
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)

Output:

(1, 2, 3, 4, 5)

Accessing Tuple Elements

We can access the elements of a tuple using their index value. Indexing in Python starts from 0.

Example:

# Accessing tuple elements
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0]) # Output: 1
print(my_tuple[2]) # Output: 3

Slicing Tuples

We can also slice a tuple to get a subset of elements. Slicing works the same way as it does with lists in Python.

Example:

# Slicing a tuple
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4]) # Output: (2, 3, 4)

Tuples are Immutable

Once a tuple is created, we cannot modify it. We cannot add or remove elements from a tuple. This makes tuples very useful when we need to ensure that the data we are working with cannot be accidentally modified.

Example:

# Tuples are immutable
my_tuple = (1, 2, 3, 4, 5)
my_tuple[0] = 6 # Raises TypeError

Tuple Packing and Unpacking

Tuple packing is when we create a tuple and assign multiple values to it. Tuple unpacking is when we assign the values of a tuple to multiple variables.

Example:

# Tuple packing and unpacking
my_tuple = (1, 2, 3, 4, 5)
a, b, c, d, e = my_tuple # Unpacking tuple values into variables
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
print(d) # Output: 4
print(e) # Output: 5

my_new_tuple = 6, 7, 8 # Packing multiple values into a tuple
print(my_new_tuple) # Output: (6, 7, 8)

Tuples as Function Arguments

Tuples can be used as function arguments in Python. This allows us to pass multiple values to a function using a single variable.

Example:

# Using tuples as function arguments
def my_function(*args):
  for arg in args:
    print(arg)

my_tuple = (1, 2, 3, 4, 5)
my_function(*my_tuple) # Unpacking tuple values into function arguments

Output:

1
2
3
4
5

Conclusion

Tuples are an important data structure in Python, and they can be used in many different ways. They are immutable and ordered, which makes them useful in situations where we need to ensure that our data cannot be accidentally modified. Tuples can be used as function arguments, and they can be packed and unpacked to allow us to work with multiple values at once.