🌀 Python Tuples 

🔹 1. What is a Tuple?

A tuple is an ordered, immutable (unchangeable) collection of items.
It can store different data types, just like a list.

✅ Example:

t1 = (10, 20, 30)
t2 = ("Sakshi", 9.4, True)
 

✅ Empty Tuple:

 

empty = ()

✅ Single Element Tuple (don’t forget the comma):

single = (5,)   # Tuple
not_tuple = (5) # Just an integer
 

🔹 2. Creating Tuples

tuple1 = (1, 2, 3)
tuple2 = ("apple", "banana", "cherry")
tuple3 = tuple([10, 20, 30])   # from list
 

🔹 3. Accessing Elements (Indexing & Slicing)

✅ Example:

colors = ("red", "green", "blue", "yellow")
print(colors[0])    # red
print(colors[-1])   # yellow
print(colors[1:3])  # ('green', 'blue')
 

🔹 4. Immutability

You cannot change or delete tuple elements.

❌ Example (Error):

t = (1, 2, 3)
t[0] = 10   # TypeError
 

✅ You can reassign the variable though:

t = (1, 2, 3)
t = (4, 5, 6)   # New tuple created
 

🔹 5. Tuple Operations

OperationExampleOutput
Concatenation(1, 2) + (3, 4)(1, 2, 3, 4)
Repetition("Hi",) * 3('Hi', 'Hi', 'Hi')
Membership"a" in ("a", "b")True
Lengthlen(t)
Indext.index(x)returns index of first occurrence
Countt.count(x)counts how many times x appears

✅ Example:

t = (1, 2, 2, 3, 4)
print(len(t))        # 5
print(t.count(2))    # 2
print(t.index(3))    # 3rd position → index 3
 

🔹 6. Iterating Through Tuples

✅ Example:

fruits = ("apple", "banana", "cherry")
for f in fruits:
   print(f)
 

🔹 7. Tuple Packing and Unpacking

✅ Example:

student = ("Sakshi", 9.4, "CSE")
name, sgpa, branch = student
print(name)   # Sakshi
print(sgpa)   # 9.4
 

🔹 8. Nested Tuples

✅ Example:

nested = ((1, 2), (3, 4), (5, 6))
print(nested[1][0])   # 3
 

🔹 9. Tuple Functions

Python Tuples - The immutable sequence of objects - TechVidvan
FunctionDescriptionExample
len()Number of elementslen(t)
max()Largest valuemax((10, 20, 5)) → 20
min()Smallest valuemin((10, 20, 5)) → 5
sum()Sum of numeric valuessum((1,2,3)) → 6
sorted()Returns sorted listsorted((3,1,2)) → [1,2,3]

🔹 10. Why Use Tuples?

✅ Tuples are:

Faster than lists (because immutable).

Memory efficient.

Hashable (can be used as keys in dictionaries).

Safe (data can’t be modified accidentally).

🧠 Mini Practice Programs

  1. Create a tuple of numbers and find their sum.
  2. Find the maximum and minimum value in a tuple.
  3. Count how many times a value appears in a tuple.
  4. Convert a list into a tuple.
  5. Create a nested tuple and access elements inside it.