Python Tuples

Python Tuples

Tuples are used to store multiple items in a single variable. A tuple is a collection which is ordered and unchangeable (immutable).

Tuples are written with round brackets ().

Create a Tuple

thistuple = ("apple", "banana", "cherry")
print(thistuple)

Access Tuple Items

You can access tuple items by referring to the index number, inside square brackets, exactly like you do with lists!

Access Example

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

Update Tuples (Workarounds)

Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created.

But there is a workaround! You can convert the tuple into a list, change the list, and convert the list back into a tuple.

Update Tuple Workaround

x = ("apple", "banana", "cherry")

// Convert to list to modify y = list(x) y[1] = "kiwi"

// Convert back to tuple x = tuple(y)

print(x)


Exercise

?

What is a core characteristic of a Python tuple?