13.1 Adding Elements
Tuples are immutable objects. Once a tuple is created, it cannot be changed. But often, even if an object can't be modified, we may need its modified copy.
This is exactly what is done with the str class — it has a couple dozen methods that do not change the original str object but return a new string corresponding to the essence of the method called.
Python developers could have added methods to the tuple class that would return a new object when trying to change a tuple. But they didn't. Maybe to avoid confusing us, or for some other reason.
So all tuple modifications follow this plan:
list_ = list(tuple_)
modify the list_ here
tuple2 = tuple(list_)
append():
For instance, if you want to add an element to a tuple, here's how it might look:
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
my_list.append(4) # add element to list
my_new_tuple = tuple(my_list)
Adding a Group of Elements — method extend():
The extend() method allows you to add multiple elements to a list at once. The method accepts an iterable (e.g., another list, tuple, set) as an argument:
my_tuple = (1, 2, 3, 4)
my_list = list(my_tuple)
my_list.extend((5, 6)) # add elements to list
my_new_tuple = tuple(my_list)
Inserting in the Middle — method insert()
The insert() method adds an element at a specified position in a list. It takes two arguments: the index where the element should be placed, and the element itself:
my_tuple = (1, 2, 3, 4)
my_list = list(my_tuple)
my_list.insert(0, 0) # add 0 to the beginning of the list
my_new_tuple = tuple(my_list)
13.2 Modifying Elements
If you need to change an element of a tuple, proceed with the plan:
list_ = list(tuple_)
# modify the list_ here
tuple2 = tuple(list_)
Let's assign the first element of the tuple the last value, and the last — the first one. Here's the code we'll need:
my_tuple = (1, 2, 3, 4)
my_list = list(my_tuple)
my_list[0], my_list[-1] = my_list[-1], my_list[0] # swap values
my_new_tuple = tuple(my_list)
print(my_new_tuple) # (4, 2, 3, 1)
13.3 Removing Elements
Remove elements from a tuple following the same plan.
Let's provide an example where we want to remove a specific value from a tuple
atuple = ("apple", "banana", "cherry")
alist = list(atuple)
alist.remove("apple")
atuple = tuple(alist)
print(atuple) # ('banana', 'cherry')
Note that in the end, we assign the new tuple object to a variable that previously held the reference to the original tuple. You can do this, but the original tuple won't change. If there's a reference to it somewhere earlier in the code, it'll continue to point to the original tuple.
Now let's remove the last element from the tuple.
Here's what the code will look like:
atuple = ("apple", "banana", "cherry")
alist = list(atuple)
alist.pop() # remove last element
atuple = tuple(alist)
print(atuple) # ('apple', 'banana')
I think you get the idea. You can't delete elements from a tuple, but if you really want to, you can 😊
GO TO FULL VERSION