Tuples in Python
A tuple is an ordered, immutable collection of elements that allows duplicates. Unlike lists, tuples cannot be modified after creation, making them useful for fixed data structures.
🔹 Tuple Operations
📌 Good for: Ordered, immutable, allows duplicates
Basic Operations
tuple[i]
→ Access element at indexi
t = (10, 20, 30)
print(t[1]) # Output: 20
tuple[i:j]
→ Slice fromi
toj-1
t = (10, 20, 30, 40)
print(t[1:3]) # Output: (20, 30)
tuple.count(x)
→ Count occurrences ofx
t = (1, 2, 2, 3, 4, 2)
print(t.count(2)) # Output: 3
tuple.index(x)
→ Find first occurrence ofx
t = (10, 20, 30, 40)
print(t.index(30)) # Output: 2
tuple + tuple2
→ Concatenation
t1 = (1, 2, 3)
t2 = (4, 5, 6)
print(t1 + t2) # Output: (1, 2, 3, 4, 5, 6)
tuple * n
→ Repeatn
times
t = (1, 2)
print(t * 3) # Output: (1, 2, 1, 2, 1, 2)
len(tuple)
→ Get length
t = (10, 20, 30)
print(len(t)) # Output: 3
Tuple Unpacking
Tuples allow unpacking values into separate variables.
a, b, c = (1, 2, 3)
print(a, b, c) # Output: 1 2 3
Conversion
Convert list or set to a tuple.
lst = [1, 2, 3]
t = tuple(lst)
print(t) # Output: (1, 2, 3)
s = {4, 5, 6}
t = tuple(s)
print(t) # Output: (4, 5, 6) (unordered due to set behavior)