🐍 Tuple

list

Good to know

⭐️ Tuples are like lists, but immutable (cannot be changed after creation). They preserve order and allow duplicates. Tuples excel when you need fixed collections, safe data, or dictionary keys.


Creating Tuples

tools = ("fork", "spoon", "knife")
nums = (1, 2, 3, 3)
single = ("one",)     # comma required for single-element tuple
tuple_from_list = tuple([1, 2, 3]) # takes list & turns into (1,2,3)

Unpacking Tuples

item1, item2, item3 = tools
# fork, spoon, knife

With the star operator:

first, *rest = nums
# first = 1, rest = [2, 3, 3]

Using Tuples as Dictionary Keys

⭐️ Tuples can be used as keys because they are immutable.

coords = {}
coords[(10, 20)] = "Tree"

Manipulate tuples

Accessing Elements

first = tools[0]
last = tools[-1]
part = tools[1:3]     # slicing works like with lists

Modify

tools[1] = "bowl"   # ❌ ERROR – cannot modify

To “modify”, create a new tuple:

new_tools = tools + ("bowl",)

Tuple Methods

nums.count(3)     # how many times 3 appears
nums.index(3)     # first index of 3