Python Tuples: Immutable Data Structures

Introduction

A tuple in Python is an ordered collection of values that can be of different data types such as integers, floats, strings, etc. Unlike lists, tuples are immutable, which means that once a tuple is created, its values cannot be modified.

In this article, we will explore what Python tuples are, how they are created, and how they are used in Python programming.

Tuples are denoted by enclosing the values in parentheses (), separated by commas. For example, the following is a tuple of three integers:


my_tuple = (1, 2, 3)

Alternatively, you can define a tuple without using parentheses by separating the elements with commas, but it is a good practice to use them to avoid confusion with other data types. Here is an example:


my_tuple = 1, 2, 3, 4, 5

Creating a Tuple in Python

Tuples can be created in different ways in Python. Here are some examples:


# Creating an empty tuple
my_tuple = ()

# Creating a tuple with a single value
my_tuple = (1,)

# Creating a tuple with multiple values
my_tuple = (1, 2, 3)

# Creating a tuple with values of different data types
my_tuple = ('hello', 3.14, True)

As mentioned earlier, tuples are immutable, which means that their values cannot be changed once they are created. However, we can create a new tuple by concatenating two or more tuples using the ā€˜+ā€˜ operator. For example:


tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
new_tuple = tuple1 + tuple2
print(new_tuple)
# Output: (1, 2, 3, 'a', 'b', 'c')

Accessing Tuple Elements

Tuples are ordered collections, which means that each element in a tuple has a specific index. We can access individual elements in a tuple using their index. The first element in a tuple has an index of 0, the second element has an index of 1, and so on.

Here is an example of how to access elements in a tuple:


my_tuple = ('apple', 'banana', 'cherry')
print(my_tuple[0])  # Output: 'apple'
print(my_tuple[1])  # Output: 'banana'
print(my_tuple[2])  # Output: 'cherry'

We can also use negative indexing to access elements from the end of the tuple. The last element has an index of -1, the second-last element has an index of -2, and so on.


my_tuple = ('apple', 'banana', 'cherry')
print(my_tuple[-1])  # Output: 'cherry'
print(my_tuple[-2])  # Output: 'banana'
print(my_tuple[-3])  # Output: 'apple'

Tuple Slicing

Like lists, we can also use slicing to extract a subset of a tuple. Slicing a tuple returns a new tuple that contains the selected elements.

Here is an example of tuple slicing:


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

How to append elements to a Python Tuple

As tuples are immutable, it is not possible to append elements to an existing tuple. Nevertheless, there are alternative approaches to achieve this. The subsequent guidelines can aid us in accomplishing this task.

Steps:

  1. Convert the Tuple to a Python List.
  2. Execute the appending operation on the list to insert the new element.
  3. Convert the list back to a tuple once more.

For example:


my_tuple = (1, 2, 3, 4)

# Converting my_tuple to a list
my_list = list(my_tuple)

# Appending a new item to the list
my_list.append(5)

# Converting back to a Tuple once more
my_new_tuple = tuple(my_list)

print(my_new_tuple) # (1, 2, 3, 4, 5)

Note that the above approach creates new tuples, and the original tuples remain unchanged.

How to remove elements from a Python Tuple

Due to the immutable nature of tuples, it is not possible to remove individual elements from a tuple directly. However, you can create a new tuple that contains only the elements you want to keep, effectively ā€œremovingā€ the unwanted elements. Here are a few approaches to remove elements from a tuple:

1. Using slicing: You can use slicing to create a new tuple that excludes the elements you want to remove. Here is an example:


my_tuple = (1, 2, 3, 4, 5)
new_tuple = my_tuple[:2] + my_tuple[3:]
print(new_tuple) # Output: (1, 2, 4, 5)

In this example, a new tuple ā€˜new_tupleā€˜ is created by concatenating two slices of the original tuple ā€˜my_tupleā€˜. The first slice includes the elements from index 0 to index 1, and the second slice includes the elements from index 3 to the end of the tuple, effectively removing the element at index 2.

2. Using filter() function: You can use the ā€˜filter()ā€˜ function to create a new tuple that excludes the elements you want to remove based on a condition. Here is an example:


my_tuple = (1, 2, 3, 4, 5)
new_tuple = tuple(filter(lambda x: x != 3, my_tuple))
print(new_tuple) # Output: (1, 2, 4, 5)

In this example, the ā€˜filter()ā€˜ function is used to create a new tuple ā€˜new_tupleā€˜ that excludes the element 3 from the original tuple ā€˜my_tupleā€˜.

3. Using list conversion: You can convert the tuple to a list, remove the unwanted elements using list methods, and then convert the list back to a tuple. Here is an example:


my_tuple = (1, 2, 3, 4, 5)
my_list = list(my_tuple)
my_list.remove(3)
new_tuple = tuple(my_list)
print(new_tuple) # Output: (1, 2, 4, 5)

In this example, the original tuple ā€˜my_tupleā€˜ is converted to a list ā€˜my_listā€˜, and the element 3 is removed using the ā€˜remove()ā€˜ method. Finally, the modified list is converted back to a tuple ā€˜new_tupleā€˜.

It is important to note that these approaches create new tuples, and the original tuples remain unchanged.

Advantages of using Tuple

  • Tuples are faster than lists since they are immutable and cannot be modified. This means they do not require as much memory and can be accessed and processed quickly.
  • Tuples are useful for returning multiple values from a function.
  • Tuples can be used as keys in dictionaries, whereas lists cannot.
  • Tuples can be used in situations where immutability is desired, such as database records and configuration settings.

Exercises

Try some exercises for practicing Python tuples:

  1. Write a program that creates a tuple of integers from 1 to 10 and prints the tuple in reverse order.
  2. Write a function that accepts two tuples of equal length and returns a new tuple that contains the sum of corresponding elements of the two tuples.
  3. Write a program that prompts the user to enter a sequence of numbers separated by commas, creates a tuple from the numbers, and prints the tuple.
  4. Write a program that creates a tuple of strings and prints the tuple in alphabetical order.
  5. Write a program that prompts the user to enter a sentence, creates a tuple of words from the sentence, and prints the tuple.
  6. Write a program that creates a tuple of random numbers and calculates the sum and average of the numbers in the tuple.
  7. Write a program that creates a tuple of dates and sorts them in chronological order.
  8. Write a program that creates a tuple of dictionaries and prints the value of a specific key in each dictionary.
  9. Write a program that creates a tuple of nested tuples and prints the second element of each nested tuple.
  10. Write a program that creates a tuple of random numbers and removes all odd numbers from the tuple.

These exercises cover a wide range of topics related to tuples in Python, such as creating tuples, indexing, slicing, sorting, iterating, and manipulating tuples.

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! Iā€™m Subhankar Rakshit, the brains behind PySeek. Iā€™m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles:Ā 194