Lesson 42 +10 XP

Access and Update Tuples

Reading a tuple is like reading a list. Changing one takes a trick.

Access by index and range


python
thistuple = ("apple", "banana", "cherry", "orange")
print(thistuple[1])

### banana
print(thistuple[1:3])

### ('banana', 'cherry')

Check if an item exists


python
if "apple" in thistuple:
    print("Yes, apple is in the tuple")

Tuples can't change... directly


python
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:


python
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)

### ('apple', 'kiwi', 'cherry')

Add items (with the same trick)


python
y = list(x)
y.append("orange")
x = tuple(y)

Remove items


python
y = list(x)
y.remove("apple")
x = tuple(y)

Or build a new tuple from a slice:


python
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.