Python Tuple Methods & Joining
A tuple has only two methods of its own, count() and index(). The plus sign joins tuples into a new tuple.
Count a value with count()
count() tells you how often a value appears.
rolls = (2, 5, 2, 6, 2)
print(rolls.count(2))
print(rolls.count(4))Find a position with index()
index() gives the position of the first match.
days = ("Mon", "Tue", "Wed")
print(days.index("Tue"))Join tuples with +
The plus sign builds one new tuple.
first = (1, 2)
second = (3, 4)
print(first + second)Repeat a tuple with *
The star repeats the items to make a longer tuple.
pattern = ("go",)
print(pattern * 3)Biggest, smallest, and total
These built-in tools work on tuples of numbers.
steps = (4000, 6500, 5200)
print(max(steps))
print(min(steps))
print(sum(steps))Example
week_one = (5200, 6100, 4800, 7000)
week_two = (5600, 6300, 5900, 7200)
all_steps = week_one + week_two
print(all_steps)
print("Days:", len(all_steps))
print("Best day:", max(all_steps))
print("Total:", sum(all_steps))Key points
- Method: a tool that belongs to a value, called with a dot
- Tuples have only two methods, count() and index()
- Use count() to count how often a value appears
- Use index() to find the first position of a value
- Use + to join tuples into a new tuple
- Use * to repeat a tuple
- Use max(), min(), and sum() on a tuple of numbers
- Check with in first if you are not sure.
In this example, week_one and week_two each hold four days of steps. The plus sign joins them into one new tuple called all_steps. print(all_steps) shows all eight days in order. len(all_steps) gives 8 days in total. max(all_steps) finds the best day, with 7200 steps. sum(all_steps) adds every day and gives 48100.
Note
index() raises ValueError when the value is not in the tuple.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What is (1, 2) + (3,) ?