Python Tuples

🐍 Python Tuples — Full Tutorial

A Tuple in Python is a collection of ordered, unchangeable (immutable) items.

Tuples are written using parentheses ():

my_tuple = ("Apple", "Banana", "Cherry")

✅ 1. Creating a Tuple

fruits = ("Apple", "Banana", "Cherry")
numbers = (1, 2, 3, 4)
mixed = (10, "Hello", True, 5.5)

Empty Tuple:

empty = ()

Tuple with One Item (Important):

Use a comma, otherwise Python treats it as a normal variable:

single = ("Apple",) # Correct
not_tuple = ("Apple") # Wrong (this is a string)

🔹 2. Accessing Tuple Items (Indexing)

fruits = ("Apple", "Banana", "Cherry")

print(fruits[0]) # Apple
print(fruits[-1]) # Cherry


🔹 3. Tuple Slicing

fruits = ("Apple", "Banana", "Cherry", "Mango", "Orange")

print(fruits[1:4]) # ('Banana', 'Cherry', 'Mango')
print(fruits[:3]) # ('Apple', 'Banana', 'Cherry')


🔹 4. Tuples are Immutable ❌ (Cannot Change)

fruits = ("Apple", "Banana", "Cherry")
# fruits[1] = "Kiwi" # ERROR ❌

🔹 5. But You Can Convert Tuple → List → Tuple ✔

fruits = ("Apple", "Banana", "Cherry")

temp = list(fruits)
temp[1] = "Kiwi"
fruits = tuple(temp)

print(fruits)


🔹 6. Adding Items to a Tuple

Since tuples cannot be directly modified, we do:

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

t3 = t1 + t2

print(t3) # (1, 2, 3, 4, 5)


🔹 7. Removing Items (Not Allowed)

But you can delete the entire tuple:

fruit = ("Apple", "Banana")
del fruit

🔹 8. Looping Through a Tuple

fruits = ("Apple", "Banana", "Cherry")

for item in fruits:
print(item)


🔹 9. Check if an Item Exists

fruits = ("Apple", "Banana")

print("Apple" in fruits) # True
print("Kiwi" not in fruits) # True


🔹 10. Tuple Methods

Method Action
count() Counts occurrences
index() Returns index of value

Example:

t = (1, 2, 2, 3, 2)

print(t.count(2)) # 3
print(t.index(3)) # 3rd position


🔹 11. Tuple Packing and Unpacking

info = ("John", 25, "India")

name, age, country = info

print(name)
print(age)
print(country)


🔁 Unpack with * (Variable Length Items)

numbers = (1, 2, 3, 4, 5)

a, b, *c = numbers

print(a) # 1
print(b) # 2
print(c) # [3, 4, 5]


🔹 12. Nested Tuples

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

🔹 13. Tuple vs List

Feature Tuple List
Syntax () []
Mutable ❌ No ✔ Yes
Faster ✔ Yes ❌ No
Use Case Fixed data Changing data

🧠 When to Use Tuples?

✔ Store fixed data (like dates, coordinates, constant values)
✔ Faster performance
✔ Protect data from modification

Example:

colors = ("Red", "Green", "Blue")

⭐ Mini Project: Student Record

student = ("Amit", 21, "Python", 95)

name, age, course, score = student

print(f"Name: {name}")
print(f"Age: {age}")
print(f"Course: {course}")
print(f"Score: {score}")

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *