Facebook Pixel

Manipulating Tuples

In the previous section, we learned that tuples are immutable. Because of this, we cannot directly modify their items. Tuples are immutable, hence if you want to add, remove or change tuple items, then first you must convert the tuple to a list. Then perform operations on that list and convert it back to a tuple.

Example:

countries = ("Spain", "Italy", "India", "England", "Germany")
temp = list(countries)
temp.append("Russia")       # add item 
temp.pop(3)                 # remove item
temp[2] = "Finland"         # change item
countries = tuple(temp)
print(countries)

Output:

('Spain', 'Italy', 'Finland', 'Germany', 'Russia')

Thus, we convert the tuple to a list, manipulate items of the list using list methods, then convert the list back to a tuple.

However, we can directly concatenate two tuples instead of converting them to a list and back.

Example:

countries = ("Pakistan", "Afghanistan", "Bangladesh", "SriLanka")
countries2 = ("Vietnam", "India", "China")
southEastAsia = countries + countries2
print(southEastAsia)

Output:

('Pakistan', 'Afghanistan', 'Bangladesh', 'SriLanka', 'Vietnam', 'India', 'China')
```~~