Tuple Methods & Uses
Tuples have only two built-in methods, but they are very useful. Tuples shine as lightweight records and dictionary keys.
count() & index()
t = (1, 2, 3, 2, 4, 2, 5)
print(t.count(2)) # 3
print(t.index(3)) # 2 (first occurrence)
print(t.index(2)) # 1 (first occurrence)Tuple vs List
import sys
lst = [1, 2, 3, 4, 5]
tup = (1, 2, 3, 4, 5)
print(sys.getsizeof(lst)) # larger
print(sys.getsizeof(tup)) # smaller
# Tuples are faster to iterate and unpackTuples as Dict Keys
# Lists cannot be dict keys (unhashable)
locations = {}
locations[(40.7128, -74.0060)] = "New York"
locations[(51.5074, -0.1278)] = "London"
print(locations[(40.7128, -74.0060)]) # New YorkReturning Multiple Values
def min_max(lst):
return min(lst), max(lst)
lo, hi = min_max([3, 1, 4, 1, 5, 9])
print(lo, hi) # 1 9