Python Tuple - Detailed Explanation

1. What is a Tuple?

Tuple in Detail

A tuple in Python is a collection data type that is:

my_tuple = (10, 20, 30, "hello", 3.14)
print(my_tuple)   # (10, 20, 30, 'hello', 3.14)

2. Creating Tuples

Tuples are created using () or without parentheses:

# With parentheses
numbers = (1, 2, 3)

# Without parentheses (tuple packing)
student = "Alice", 21, "CS"

# Single element tuple must have a comma
x = (5,)   # tuple
y = (5)    # just an integer

3. Accessing Tuple Elements

student = ("Alice", 21, "CS")

print(student[0])   # Alice
print(student[-1])  # CS (negative index)

4. Tuple Immutability

Tuples cannot be modified after creation:

numbers = (1, 2, 3)
numbers[0] = 10   # ❌ Error: 'tuple' object does not support item assignment

5. Tuple Methods

Tuples have only a few built-in methods:

MethodDescriptionExample
count() Returns number of occurrences of an element
t = (1,2,2,3)
print(t.count(2))   # 2
index() Returns the index of first occurrence of an element
t = (1,2,3,2)
print(t.index(3))   # 2

6. Tuple Operations

t1 = (1, 2)
t2 = (3, 4)

# Concatenation
print(t1 + t2)  # (1, 2, 3, 4)

# Repetition
print(t1 * 3)   # (1, 2, 1, 2, 1, 2)

# Membership
print(2 in t1)   # True

7. Uses of Tuples

# Returning multiple values
def get_student():
    return ("Alice", 21, "CS")

name, age, course = get_student()
print(name, age, course)  # Alice 21 CS

8. Tuple vs List

FeatureListTuple
Syntax[1, 2, 3](1, 2, 3)
Mutable?✅ Yes❌ No
PerformanceSlowerFaster
Use caseWhen data changesWhen data is constant