Some text some message..
Back 10 🔷 What is a Tuple in Python? 23 Jun, 2025

A tuple is an ordered, immutable collection of elements. It can store elements of different data types and is defined using parentheses ().


🧠 Key Characteristics

Feature Description
Ordered Elements have a fixed position/index
Immutable Cannot be changed (no add/remove/update)
Allows Duplicates Yes
Heterogeneous Can contain different data types (int, str, etc)

✅ Syntax of a Tuple

my_tuple = (10, "apple", 3.14)

🧪 Examples

➤ 1. Creating a Tuple

empty_tuple = ()
single_element_tuple = (5,)       # Notice the comma
mixed_tuple = (1, "Hello", 3.14)

Note: A single-element tuple must have a comma, otherwise it's not a tuple.


➤ 2. Accessing Tuple Elements (Indexing)

t = (10, 20, 30, 40)
print(t[0])   # Output: 10
print(t[-1])  # Output: 40 (last element)

➤ 3. Slicing Tuples

print(t[1:3])  # Output: (20, 30)

➤ 4. Tuple Packing and Unpacking

# Packing
person = ("Abhi", 30, "Data Scientist")

# Unpacking
name, age, profession = person
print(name)        # Output: Abhi
print(profession)  # Output: Data Scientist

➤ 5. Tuple with Nested Structures

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

Even though tuples are immutable, if they contain a mutable object (like a list), that object can be modified.


🧰 Tuple Methods

Method Description
.count(x) Returns the number of times x appears
.index(x) Returns the index of the first x
t = (1, 2, 3, 2, 2, 4)
print(t.count(2))   # Output: 3
print(t.index(3))   # Output: 2

🔁 Looping through Tuples

for item in t:
    print(item)

❌ What You Can’t Do with Tuples

t = (1, 2, 3)
# t[0] = 10       ❌ Error: 'tuple' object does not support item assignment
# t.append(4)     ❌ Error: 'tuple' object has no attribute 'append'

🟡 When to Use Tuples?

  • Data that should not change (e.g., coordinates, days of the week)

  • As dictionary keys

  • For faster access (tuples are slightly faster than lists)


🎨 Visual Summary (Infographic Style Text)

+-----------------------------+
|         TUPLE              |
+-----------------------------+
| Ordered        ✅          |
| Immutable      ✅          |
| Duplicates     ✅          |
| Indexed        ✅          |
+-----------------------------+
| Example: (1, "a", 3.14)     |
+-----------------------------+