Overview
Python tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created. But there are some workarounds.
Change Tuple Item Values
To change tuple items, the workaround is to convert the tuple into a list, make changes to the list, and then convert the list back to a tuple.
my_tuple = ("Ferrari", "Maserati", "Alfa Romeo")
my_list = list(my_tuple)
my_list[0] = "Lamborghini"
my_tuple = tuple(my_list)
print(my_tuple) #('Lamborghini', 'Maserati', 'Alfa Romeo')
Note
Arrays count starting from zero NOT one. So item 1 is position [0], item 2 is position [1], and item 3 is position [2] … and so on.
Adding Items
To add tuple items, convert the tuple into a list, add items to the list, and then convert the list back to a tuple.
my_tuple = ("Ferrari", "Maserati", "Alfa Romeo")
my_list = list(my_tuple)
my_list.append("Lamborghini")
my_tuple = tuple(my_list)
print(my_tuple) #('Ferrari', 'Maserati', 'Alfa Romeo', 'Lamborghini')
Removing Items
To remove tuple items, convert the tuple into a list, remove items from the list, and then convert the list back to a tuple.
my_tuple = ("Ferrari", "Maserati", "Alfa Romeo")
my_list = list(my_tuple)
my_list.remove("Ferrari")
my_tuple = tuple(my_list)
print(my_tuple) #('Maserati', 'Alfa Romeo')
Adding a Tuple to a Tuple
Adding a tuple, or multiple tuples, to a tuple is allowed.
my_tuple = ("Ferrari", "Maserati", "Alfa Romeo")
new_tuple = ("Lamborghini",)
my_tuple += new_tuple
print(my_tuple) #('Ferrari', 'Maserati', 'Alfa Romeo', 'Lamborghini')
Note
To create a tuple with only one item, you have to add a comma after the item, otherwise will not be recognized it as a tuple.
Python Notes:
- The most recent major version of Python is Python 3; however, Python 2 is still in use and quite popular, although not being updated with anything other than security updates
- Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses
- Python relies on indentation, using whitespace to define scope, such as the scope of loops, functions, and classes; other programming languages often use curly-brackets for this purpose
- Python string methods return new values, and DO NOT change the original string
- Python tuples are unchangeable after created (their items CANNOT be changed or re-ordered at a later point)
- Python sets are unordered (may appear in random orders when called), unchangeable (the value of individual items cannot be changed after creation), and unindexed (items cannot be referred to by index or key)
We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.