Remove elements in tuple – Python

Tuple is an immutable datatype in Python. Elements in a tuple cannot be removed (deleted) directly. To remove an element from a tuple, we need to follow following steps: convert tuple in list (mutable datatype), then remove the element from list and then convert list back to tuple.

Follow quick-start guide, for all topics related to tuple in Python – Tuple in Python – Quickstart

In previous article, we learned about append and change operation on tuple. Append elements in tuple and Change elements in tuple.

Remove elements in tuple

Tuple in Python is an immutable object. Immutable object means we cannot modify the tuple objects. It means we cannot perform operations like add (append), update (change) and delete (remove) on the elements in the tuple.

To remove elements from a tuple, we need to convert tuple from immutable datatype to a mutable datatype like list. To remove elements from the list we can use list_obj.remove(element). Read more about list remove method.

Error – Remove element in tuple

# remove elements from tuple - using remove function
print("remove elements from tuple - using remove function")

shbytes_tuple = ('Python', 'AWS', 'Java', 'Azure', 'Machine Learning')
print(shbytes_tuple)

shbytes_tuple.remove('Java')                                                       # remove element in tuple

In this program, we have declared and initialized a tuple which is referenced by a variable name ‘sybytes_tuple’. We are calling the ‘remove’ method on the ‘sybytes_tuple’, to remove element ‘Java’ from this tuple. Since, tuples are immutable objects, this remove operation will give an AttributeError.

Program Output

Traceback (most recent call last):
  File "D:\delete-tuple-elements.py", line 7, in <module>
    shbytes_tuple.remove('Java')
    ^^^^^^^^^^^^^^^^^^^^
AttributeError: 'tuple' object has no attribute 'remove'

remove elements from tuple - using remove function
('Python', 'AWS', 'Java', 'Azure', 'Machine Learning')

Program output shows, remove operation on tuple object gives error. AttributeError: ‘tuple’ object has no attribute ‘remove’.

Remove from tuple by converting it to list

# remove elements from tuple - by converting it to list
print("remove elements from tuple - by converting it to list")

shbytes_tuple = ('Python', 'AWS', 'Java', 'Azure', 'Machine Learning')
print(shbytes_tuple)

temp_list = list(shbytes_tuple)                                        # convert tuple into list (mutable object)
temp_list.remove("Java")                                                 # remove element from the list
new_tuple = tuple(temp_list)                                           # convert list back to tuple
print(new_tuple)

We have declared and initialized a tuple which is referenced by a variable name ‘sybytes_tuple’. First we are converting the ‘shbytes_tuple’ into a list (mutable object). We are calling the ‘remove’ method on the ‘temp_list’, to remove element ‘Java’ into this list. Then we convert list back to tuple (immutable object).

Program Output

remove elements from tuple - by converting it to list
('Python', 'AWS', 'Java', 'Azure', 'Machine Learning')
('Python', 'AWS', 'Azure', 'Machine Learning')

Program output shows, element ‘Java’ was removed the tuple.

Remove in mutable elements in nested tuple

# remove in mutable elements in tuple
print("remove in mutable elements in tuple")

nested_tuple = ('Python', 'AWS', 'Azure', [1, 2, 3])              # nested tuple with a list element at index 3
print("original nested tuple", nested_tuple)                      # print initial tuple elements

nested_tuple[3].remove(2)                                         # remove 2 from list element, which is at index 3 in nested tuple
print("changed mixed tuple", nested_tuple)             # print changed tuple elements

We have declared and initialized a nested tuple which is referenced by a variable name ‘nested_tuple’. Nested tuple element [1, 2, 3] is at index 3 of the tuple. We are accessing index 3 element and then calling ‘remove’ method on that element to remove 2 from it. Since nested element is a list (mutable object) that is why we are able to call remove method on that object.

Program Output

remove in mutable elements in tuple
original mixed tuple ('Python', 'AWS', 'Azure', [1, 2, 3])
changed mixed tuple ('Python', 'AWS', 'Azure', [1, 3])

First we are printing initial elements from the tuple. In the second print, 2 was removed from the nested list element.

Program – Error – Element not in tuple

# Error - element not in tuple

shbytes_tuple = ('Python', 'AWS', 'JAVA', 'Azure', 'Machine Learning')
print(shbytes_tuple)

temp_list = list(shbytes_tuple)                            # Convert tuple into a list
temp_list.remove("GoLang")                               # Remove element 'GoLang' from the list
new_tuple = tuple(temp_list)                               # Convert list into a tuple

First we are converting tuple into a list and then on the list, we are calling remove(element) method to remove ‘GoLang’ from list. But, ‘GoLang’ is not present in the tuple and will not be present into the list as well. This will throw an error – element not in list.

Program Output

('Python', 'AWS', 'JAVA', 'Azure', 'Machine Learning')
Traceback (most recent call last):
  File "D:\My Work\Trainings\Code-Repo\training-documents\Python-Training-tuples-in-python-tuples-in-python-programs-delete-tuple-elements.py", line 47, in <module>
    temp_list.remove("GoLang")
ValueError: list.remove(x): x not in list

On the call of remove(element) method, program throws an error. ValueError: list.remove(x): x not in list

Program – Error – Case-sensitive element not in tuple

# Error - Case-sensitive element not in tuple

shbytes_tuple = ('Python', 'AWS', 'JAVA', 'Azure', 'Machine Learning')
print(shbytes_tuple)

temp_list = list(shbytes_tuple)                                        # Convert tuple into a list
temp_list.remove("java")                                                  # Remove case-sensitive element 'java' from the list
new_tuple = tuple(temp_list)                                           # Convert list into a tuple

First we are converting tuple into a list and then on the list, we are calling remove(element) method to remove ‘java’ from the list. Note, element is in small case letters. ‘JAVA’ (in capital letters) is present in tuple. remove(element) method will check for case-sensitivity before deleting an element. This will throw an error – element not in list.

Program Output

('Python', 'AWS', 'JAVA', 'Azure', 'Machine Learning')

Traceback (most recent call last):
  File "D:\delete-tuple-elements.py", line 39, in <module>
    temp_list.remove("java")
ValueError: list.remove(x): x not in list

Exact match of element with case-sensitive letters is not present in the tuple. On the call of remove(element) method, program throws an error. ValueError: list.remove(x): x not in list

Summary

In this article we learned about Remove elements in tuple. Following scenarios were explored:

Code – Github Repository

All code snippets and programs for this article and for Python tutorial, can be accessed from Github repository – Comments and Docstring in Python.

Python Topics


Interview Questions & Answers

Q: why tuples are immutable?

Tuple is a collection datatype of Python objects separated by commas. Tuples are immutable, meaning that once a tuple is created, its elements cannot be changed, added, or removed.

Tuple are immutable because of their internal design. Tuples are stored in a way that allows them to be more memory-efficient and faster than lists in certain scenarios and for some operations. Because they are immutable, the Python interpreter can optimize their storage and access patterns for tuples.

Q: How to remove multiple elements from a tuple?

To remove multiple elements from a tuple, first we can convert tuple into a list and then we can use list comprehension to remove elements from it.

numbers_tuple = (14, 26, 38, 42, 54, 64, 78)   # Original tuple
elements_to_remove = {38, 54, 78}   # Elements to remove from tuple

# Convert tuple to list and filter out the elements
new_list = [item for item in numbers_tuple if item not in elements_to_remove]
new_tuple = tuple(new_list)  # Convert list back to tuple
print(new_tuple)  # Element in new_tuple => (14, 26, 42, 64)

Q: Why should we choose a tuple over a list despite tuple is immutable?

There are some use cases in which Tuple is more beneficial compared to list.

  • When we don’t need to change the data – If the data should remain constant and not be altered, a tuple is a good choice to prevent accidental modifications.
  • For better performance – Tuples, being immutable, are generally faster and consume less memory than lists.
  • Tuple as dictionary keys – Tuples can be used as keys in dictionaries because they are hashable, while lists being mutable cannot be used as dictionary keys.
  • For data integrity – Using tuples can enhance the integrity of our data by ensuring that it remains unchanged throughout the program.

Q: Write a custom function to remove an element from a tuple by value?

Following is the program, to create custom function to remove an element from a tuple by value.

def remove_tuple_element(tuple_obj, value):
	temp_list = list(tuple_obj)  # Convert tuple to list

	if value in temp_list:
		temp_list.remove(value)  # Remove element from list if it exists

	return tuple(temp_list)      # Convert list back to tuple

# Test the function
original_tuple = (16, 42, 34, 42, 51)
new_tuple = remove_tuple_element(original_tuple, 42)
print(new_tuple)  # Elements in new_tuple => (16, 34, 42, 51)
  • In this program, we have created a function remove_tuple_element(tuple_obj, value) which take two arguments – tuple_obj and value to be removed
  • First, convert the tuple_obj into the temporary list and then remove the value from that list (ensure value exists in the list).
  • Convert the temp_list back to tuple and return that tuple from function.

Q: How can we remove an element from a tuple by index?

To remove an element from tuple by index, we can use tuple slicing to exclude the element at the specific index.

def remove_tuple_element_by_index(tuple_obj, index):
	if index < 0 or index >= len(tuple_obj):
		raise IndexError("Index out of range")

	# Return a new tuple with the element at the index removed
	return tuple_obj[:index] + tuple_obj[index + 1:]

# Test the function
original_tuple = (16, 42, 34, 42, 51)
new_tuple = remove_tuple_element_by_index(original_tuple, 1)
print(new_tuple)  # Elements in new_tuple => (16, 34, 42, 51)
  • In this program, we have created a function remove_tuple_element_by_index(tuple_obj, index), which takes two arguments tuple_obj and index position for element to be removed from this tuple.
  • Check if index given is given is within the range of given tuple_obj, if not then raise an IndexError.
  • slice the tuple_obj, excluding the index to be removed and return that new tuple.

Q: What happens if we try to remove an element from a tuple directly using a method like remove()?

Attempting to use a method like remove() on a tuple will result in an AttributeError because tuples do not have methods like remove() that are available for lists.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *