- How to change values inside tuples in Python π
- Mutable vs Immutable data types
- So what can we do to make this change?
- How can we change the data?
- Python — Update Tuples
- Change Tuple Values
- Example
- Add Items
- Example
- Example
- Remove Items
- Example
- Example
- Python β Change Tuple Values
- Examples
- 1. Update a Tuple item using a list
- 2. Remove item from a given Tuple
- Summary
- Update tuples in Python (Add, change, remove items in tuples)
- Tuples are immutable
- Append an item to a tuple
- Add/insert items to a tuple
- Change items in a tuple
- Remove items from a tuple
- Related Categories
- Related Articles
- How to change values inside tuples in Python π
- Mutable vs Immutable data types
- So what can we do to make this change?
- How can we change the data?
How to change values inside tuples in Python π
In this article we are going to discuss the differences between mutable and immutable data types and find a way to change values inside tuples. In Python we have 4 built-in data types for storing multiple values in one variable. These are lists, dictionaries, sets and tuples. These data structures can be divided into two categories. They can either be mutable or inmutable.
Mutable vs Immutable data types
The main difference is when you use mutable data types like lists or dictionaries you can change the value inside them after assignment. For example:
list_a = ["first", "second", "third"] # this is a list print(list_a) # output: ["first", "second", "third"] list_a[0] = "zero" print(list_a) # output: ["zero", "second", "third"]
However, in case of a tuple you are not able to do that, because tuples are immutable, meaning the elements inside are unchangable. If we try to change a value in our tuple like this:
tuple_a = ("element1", "element2", "element3") print(tuple_a) # output: ('element1', 'element2', 'element3') tuple_a[0] = "element0"
We will get a type error:
But sometimes we need to change a tuple’s value.
So what can we do to make this change?
The easiest solution is to use built-in conversion methods.
Okay, we have 3 remaining data types. Which one should we use? Well the _dictionaries _ require key, value pairs so in this case using a dictionary wouldn’t be a good idea. We have sets as well. Even though sets are mutable, meaning the values can be changed after assigment, they are not allowing duplicates. So converting a tuple that contains duplicate values (for example two identical string) into a set will result in data loss which we would like to avoid. So our last candidate is the list. It is mutable, allows duplicates. Seems like a perfect solution!
How can we change the data?
tuple_a = ("element1", "element2", "element3") tuple_a = list(tuple_a) print(tuple_a) # output: ["element1", "element2", "element3"] print(type(tuple_a)) # output:
After the conversion we get a list. Now we need to change the value to something else.
tuple_a = ("element1", "element2", "element3") tuple_a = list(tuple_a) print(tuple_a) # output: ["element1", "element2", "element3"] print(type(tuple_a)) # output: tuple_a[0] = "element0" print(tuple_a) # output: ["element0", "element2", "element3"]
tuple_a = ("element1", "element2", "element3") tuple_a = list(tuple_a) print(tuple_a) # output: ["element1", "element2", "element3"] print(type(tuple_a)) # output: tuple_a[0] = "element0" print(tuple_a) # output: ["element0", "element2", "element3"] tuple_a = tuple(tuple_a) print(tuple_a) # output: ("element0", "element2", "element3") print(type(tuple_a)) # output:
Python — Update Tuples
Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created.
But there are some workarounds.
Change Tuple Values
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.
Example
Convert the tuple into a list to be able to change it:
x = («apple», «banana», «cherry»)
y = list(x)
y[1] = «kiwi»
x = tuple(y)
Add Items
Since tuples are immutable, they do not have a built-in append() method, but there are other ways to add items to a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, you can convert it into a list, add your item(s), and convert it back into a tuple.
Example
Convert the tuple into a list, add «orange», and convert it back into a tuple:
2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one item, (or many), create a new tuple with the item(s), and add it to the existing tuple:
Example
Create a new tuple with the value «orange», and add that tuple:
thistuple = («apple», «banana», «cherry»)
y = («orange»,)
thistuple += y
Note: When creating a tuple with only one item, remember to include a comma after the item, otherwise it will not be identified as a tuple.
Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can use the same workaround as we used for changing and adding tuple items:
Example
Convert the tuple into a list, remove «apple», and convert it back into a tuple:
Or you can delete the tuple completely:
Example
The del keyword can delete the tuple completely:
thistuple = («apple», «banana», «cherry»)
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
Python β Change Tuple Values
If you have gone through the tutorial β Python Tuples, you would understand that Python Tuples are immutable. Therefore, you cannot change values of Tuple items. But, there is a workaround.
In this tutorial, we will learn how to update or change tuple values with the help of lists.
The basic difference between a list and tuple in Python is that, list is mutable while tuple is immutable.
So, to change or update Tuple values, we shall convert our tuple to a list, update the required item and then change back the list to a tuple.
Examples
1. Update a Tuple item using a list
In this example, we have a Tuple. Following is the step by step process of what we shall do to the Tuple.
- We shall convert the tuple to a list.
- Update the required item of the list.
- Convert the list back to tuple and assign it to the original tuple.
Python Program
tuple1 = (5, 3, 2, 8, 4, 4, 6, 2) #change tuple to list list1 = list(tuple1) #update list list1[2] = 63 #change back list to tuple tuple1 = tuple(list1) print(tuple1)
2. Remove item from a given Tuple
In this example, we shall remove an item from the tuple, again using List.
Python Program
tuple1 = (5, 3, 2, 8, 4, 4, 6, 2) #change tuple to list list1 = list(tuple1) #remove an item from list list1.remove(2) #change back list to tuple tuple1 = tuple(list1) print(tuple1)
Summary
In this tutorial of Python Examples, we learned how to work around to change the values of items in Python Tuple.
Update tuples in Python (Add, change, remove items in tuples)
In Python, tuples are immutable, meaning that you cannot modify them directly, such as adding, changing, or removing items (elements). If you need to work with mutable data, use lists instead. However, if you must update a tuple, you can convert it to a list, perform the required modifications, and then convert it back to a tuple.
Note that even though terms like «add», «change», and «remove» are used for simplicity, a new object is created in reality, and the original object remains unchanged.
Tuples are immutable
Consider the following example of a tuple:
t = (0, 1, 2) print(t) # (0, 1, 2) print(type(t)) #
To access elements in a tuple, you can use indexing [] or slicing [:] , similar to lists.
Since tuples are immutable, you cannot assign a new value to an element.
# t[0] = 100 # TypeError: 'tuple' object does not support item assignment
Destructive methods (= methods that modify the original object), such as append() in lists, are not available in tuples.
# t.append(100) # AttributeError: 'tuple' object has no attribute 'append'
Append an item to a tuple
Although tuples are immutable, you can concatenate them using the + operator. In this process, the original object remains unchanged, and a new object is created.
t = (0, 1, 2) t_add = t + (3, 4, 5) print(t_add) # (0, 1, 2, 3, 4, 5) print(t) # (0, 1, 2)
Only tuples can be concatenated, not other data types like lists.
# print(t + [3, 4, 5]) # TypeError: can only concatenate tuple (not "list") to tuple
You can concatenate a list to a tuple by first converting the list to a tuple using tuple() .
print(t + tuple([3, 4, 5])) # (0, 1, 2, 3, 4, 5)
tuple() can only convert iterable objects, such as lists, to tuples. Integers ( int ) and floating-point numbers ( float ) cannot be converted.
# print(t + tuple(3)) # TypeError: 'int' object is not iterable
To append an item to a tuple, concatenate it as a single-element tuple.
Remember that a single-element tuple requires a trailing comma.
Add/insert items to a tuple
To add new items at the beginning or end of a tuple, use the + operator as mentioned earlier. However, to insert a new item at any position, you must first convert the tuple to a list.
Convert a tuple to a list using list() .
t = (0, 1, 2) l = list(t) print(l) # [0, 1, 2] print(type(l)) #
Insert an item using insert() .
l.insert(2, 100) print(l) # [0, 1, 100, 2]
Convert the list back to a tuple with tuple() .
t_insert = tuple(l) print(t_insert) # (0, 1, 100, 2) print(type(t_insert)) #
Change items in a tuple
You can change items in a tuple using the same approach. Convert the tuple to a list, update it, and then convert it back to a tuple.
t = (0, 1, 2) l = list(t) l[1] = 100 t_change = tuple(l) print(t_change) # (0, 100, 2)
Remove items from a tuple
Similarly, you can remove items from a tuple using the same method.
t = (0, 1, 2) l = list(t) l.remove(1) t_remove = tuple(l) print(t_remove) # (0, 2)
In the above example, remove() is used, but you can also use pop() and del .
Related Categories
Related Articles
- Deque with collections.deque in Python
- NumPy: Flip array (np.flip, flipud, fliplr)
- Duck typing with hasattr() and abstract base class in Python
- Filter (extract/remove) items of a list with filter() in Python
- Set operations in Python (union, intersection, symmetric difference, etc.)
- List of NumPy articles
- Pretty-print with pprint in Python
- Reading and saving image files with Python, OpenCV (imread, imwrite)
- pandas: Extract rows/columns from DataFrame according to labels
- Write a long string on multiple lines in Python
- pandas: Random sampling from DataFrame with sample()
- NumPy: Get the number of dimensions, shape, and size of ndarray
- Create a string in Python (single/double/triple quotes, str())
- Convert Unicode code point and character to each other (chr, ord)
- How to use a key parameter in Python (sorted, max, etc.)
How to change values inside tuples in Python π
In this article we are going to discuss the differences between mutable and immutable data types and find a way to change values inside tuples. In Python we have 4 built-in data types for storing multiple values in one variable. These are lists, dictionaries, sets and tuples. These data structures can be divided into two categories. They can either be mutable or inmutable.
Mutable vs Immutable data types
The main difference is when you use mutable data types like lists or dictionaries you can change the value inside them after assignment. For example:
list_a = ["first", "second", "third"] # this is a list print(list_a) # output: ["first", "second", "third"] list_a[0] = "zero" print(list_a) # output: ["zero", "second", "third"]
However, in case of a tuple you are not able to do that, because tuples are immutable, meaning the elements inside are unchangable. If we try to change a value in our tuple like this:
tuple_a = ("element1", "element2", "element3") print(tuple_a) # output: ('element1', 'element2', 'element3') tuple_a[0] = "element0"
We will get a type error:
But sometimes we need to change a tuple’s value.
So what can we do to make this change?
The easiest solution is to use built-in conversion methods.
Okay, we have 3 remaining data types. Which one should we use? Well the _dictionaries _ require key, value pairs so in this case using a dictionary wouldn’t be a good idea. We have sets as well. Even though sets are mutable, meaning the values can be changed after assigment, they are not allowing duplicates. So converting a tuple that contains duplicate values (for example two identical string) into a set will result in data loss which we would like to avoid. So our last candidate is the list. It is mutable, allows duplicates. Seems like a perfect solution!
How can we change the data?
tuple_a = ("element1", "element2", "element3") tuple_a = list(tuple_a) print(tuple_a) # output: ["element1", "element2", "element3"] print(type(tuple_a)) # output:
After the conversion we get a list. Now we need to change the value to something else.
tuple_a = ("element1", "element2", "element3") tuple_a = list(tuple_a) print(tuple_a) # output: ["element1", "element2", "element3"] print(type(tuple_a)) # output: tuple_a[0] = "element0" print(tuple_a) # output: ["element0", "element2", "element3"]
tuple_a = ("element1", "element2", "element3") tuple_a = list(tuple_a) print(tuple_a) # output: ["element1", "element2", "element3"] print(type(tuple_a)) # output: tuple_a[0] = "element0" print(tuple_a) # output: ["element0", "element2", "element3"] tuple_a = tuple(tuple_a) print(tuple_a) # output: ("element0", "element2", "element3") print(type(tuple_a)) # output: