Tuples
This is a free course. Log in to run the code exercises and track your progress.
Tuples
A tuple is an ordered, immutable sequence written in round brackets: t = (10, 20, 30). A tuple with one element needs a trailing comma, (5,), because (5) is just the number 5.
Indexing, slicing, concatenation, repetition, membership, len(), min(), max(), sum(), sorted(), count() and index() all work as for lists. Methods that would change the tuple, such as append, do not exist, and t[0] = 1 raises a TypeError.
student = ("Asha", 17, "XI-A")
name, age, section = student # tuple unpacking
print(name, section) # Asha XI-A
point = (3, 4), (6, 8) # a nested tuple
print(point[1][0]) # 6
t = tuple([1, 2, 3]) # list to tuple
Use a tuple for a record that should not change, such as a date or a (latitude, longitude) pair. A function can return several values as a tuple: return lo, hi.
Read n, then n lines of name marks. Store each student as a (name, marks) tuple in a list, then print the name and marks of the topper (the first one on a tie).
n = int(input())
records = []
for _ in range(n):
name, marks = input().split()
records.append((name, int(marks)))
best = records[0]
# find the record with the highest marks
print(best[0], best[1])Log in to edit and run this code.