Skip to main content

Change Tuple Values

A tuple's values are fixed from the moment it is created. That quality is described as unchangeable, or by the term immutable.

There is a way around it, though: turn the tuple into a list, make your change there, then turn the list into a tuple again.

Example

Go through a list to change one of the values:

Prompt
Convert a tuple to a list, change the second value, convert it back to a tuple, and print the result.
Output: complete Python program

Add Items

Immutability also means tuples come without a built-in append() method. You still have other options for adding items.

1. Convert into a list: The trick for changing a tuple works here too. Turn the tuple into a list, add your item(s), then turn the result into a tuple again.

Example

Go through a list to add "orange" to the tuple:

Prompt
Convert a tuple into a list, add "orange" using append(), and convert it back into a tuple.
Output: complete Python program

Example

2. Add tuple to a tuple. Python lets you combine tuples directly. Put the item(s) you want to add, whether one or many, in a new tuple, then add it to the existing one:

Prompt
Create a tuple, then add another tuple containing "orange" to it using the += operator, and print the result.
Output: complete Python program

Remove Items

Since tuples are unchangeable, removing an item directly isn't possible. The list workaround from the previous sections does the job here as well:

Example

Go through a list to remove "apple":

Prompt
Convert a tuple into a list, remove "apple", and convert it back into a tuple.
Output: complete Python program

Example

To get rid of a whole tuple, use the del keyword:

Prompt
Create a tuple and then delete it completely using the del keyword. Then try to print it to show it raises an error.
Output: complete Python program