Tuples

 

 TUPLE in Python

πŸ‘‰ A Tuple is:

  • Ordered

  • Immutable (cannot be changed after creation)

  • Allows duplicates

  • Written inside parentheses ()

✅ Example:

# Creating a tuple

t = (10, 20, 30)

print(t)        # (10, 20, 30)


# Tuple with mixed data types

t2 = (1, "apple", 3.5, True)

print(t2)       # (1, 'apple', 3.5, True)


# Single element tuple (needs comma!)

t3 = (5,)

print(type(t3))   # <class 'tuple'>



πŸ“Œ Important Tuple Functions / Methods

⚡ Since tuples are immutable, they have fewer methods.

1. count(x) – Counts occurrences

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

print(t.count(2))   # 3


2. index(x) – Returns index of element

t = (10, 20, 30, 40)

print(t.index(30))   # 2


3. len() – Returns length

t = (1, 2, 3, 4)

print(len(t))   # 4


4. Tuple Packing and Unpacking

# Packing

t = (10, 20, 30)


# Unpacking

a, b, c = t

print(a, b, c)   # 10 20 30


5. Tuple Concatenation & Repetition

t1 = (1, 2)

t2 = (3, 4)


# Concatenation

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


# Repetition

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



πŸ”Ή Difference Between List and Tuple

Feature

List ([])

Tuple (())

Mutability

Mutable (can change)

Immutable (cannot change)

Syntax

[]

()

Methods

Many (append, insert, remove, etc.)

Few (count, index)

Performance

Slower (because mutable)

Faster (because immutable)

Use Case

When data needs modification

When data should stay fixed

Comments

Popular Posts