Python Tuple Methods

Learn essential tuple methods for working with immutable sequences

📦 Understanding Tuples

Tuples are ordered, immutable collections that can store multiple items. They're perfect for data that shouldn't change.


# Basic tuple creation
colors = ("red", "blue", "green")
point = (10, 20)
single = (42,)  # Note the comma!
                                    
2
Main Methods
Immutable
Cannot Change
Ordered
Keep Position

Tuple Methods Overview

Tuples have only 2 built-in methods because they're immutable:

🔍

count()

Count how many times a value appears

Search Count
📍

index()

Find the position of a value

Position Find

🔹 count() Method

Count how many times a value appears in the tuple


# Basic counting
numbers = (1, 2, 2, 3, 2, 4)
count = numbers.count(2)
print(count)  # 3

# Count letters
letters = ('a', 'b', 'a', 'c', 'a')
a_count = letters.count('a')
print(a_count)  # 3

# Count that doesn't exist
zero_count = numbers.count(99)
print(zero_count)  # 0
                            

🔹 index() Method

Find the first position where a value appears


# Find position
fruits = ("apple", "banana", "cherry")
pos = fruits.index("banana")
print(pos)  # 1

# Find first occurrence
numbers = (5, 10, 5, 20)
first_five = numbers.index(5)
print(first_five)  # 0

# Search in range
letters = ('a', 'b', 'c', 'b', 'd')
b_pos = letters.index('b', 2)  # Start from index 2
print(b_pos)  # 3
                            

🔹 Common Tuple Operations

Other useful things you can do with tuples


# Length
colors = ("red", "blue", "green")
print(len(colors))  # 3

# Access items
print(colors[0])    # red
print(colors[-1])   # green

# Check if item exists
print("red" in colors)     # True
print("yellow" in colors)  # False

# Slice tuples
print(colors[1:3])  # ('blue', 'green')
                            

🔹 Tuple Unpacking

Extract values from tuples into variables


# Basic unpacking
point = (10, 20)
x, y = point
print(x)  # 10
print(y)  # 20

# Multiple values
person = ("Alice", 25, "Engineer")
name, age, job = person
print(name)  # Alice
print(age)   # 25

# Swap variables
a = 5
b = 10
a, b = b, a
print(a)  # 10
print(b)  # 5
                            

🧠 Test Your Knowledge

How many built-in methods do tuples have?

What does (1,2,3).count(2) return?