Loading lessons...
Access and Update Tuples
Access and Update Tuples
Reading a tuple is like reading a list. Changing one takes a trick.
Access by index and range
thistuple = ("apple", "banana", "cherry", "orange")
print(thistuple[1]) # banana
print(thistuple[1:3]) # ('banana', 'cherry')
Check if an item exists
if "apple" in thistuple:
print("Yes, apple is in the tuple")
Tuples can't change... directly
thistuple[1] = "kiwi" # TypeError: 'tuple' object does not support item assignment
The workaround: convert to a list
To "change" a tuple, turn it into a list, change that, and convert back:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x) # ('apple', 'kiwi', 'cherry')
Add items (with the same trick)
y = list(x)
y.append("orange")
x = tuple(y)
Remove items
y = list(x)
y.remove("apple")
x = tuple(y)
Or build a new tuple from a slice:
x = x[:1] + x[2:]
TL;DR
- Index and slice tuples like lists.
- You cannot change a tuple in place.
- Convert to a list, modify, convert back.
- Or use slicing to build a new tuple.