+91 81900 98289

Tuple Methods

This Tuple Methods lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

A tuple has two methods. count reports how many times a value appears. index reports the first position of a value.

There is no append. When the values must change, build a new tuple or start with a list.

Example 1: Start here

index raises an error when the value is missing.

scores = (82, 74, 82) # a tuple; a fixed group of values print(scores.count(82)) # how many times it appears print(scores.index(74)) # where the first match sits

Example 2: Count a value

count works the same way it does on a list.

ranks = (1, 2, 2, 3) # a tuple; a fixed group of values print(ranks.count(2)) # how many times it appears

Example 3: Find an index

index returns the first position of the value.

ranks = (1, 2, 2, 3) # a tuple; a fixed group of values print(ranks.index(3)) # where the first match sits

Example 4: Loop the items

You can loop a tuple even though you cannot change its items.

for city in ("Chennai", "Pune"): # repeat the indented lines once per value print(city)
index raises an error when the value is missing.
Call Now 81900 98289