Spex3
    

Python Data Structures: Tuples 🔗


    

    

A tuple is an ordered, immutable (unchangeable) collection of elements. Tuples are similar to lists, but they cannot be modified after creation.

1️⃣ Creating Tuples
🔹 Basic Tuple Creation
Tuples are created using parentheses ().


fruits = ("apple", "banana", "cherry")
numbers = (1, 2, 3, 4, 5)
mixed = (1, "hello", 3.14, True)

🔹 Single-Element Tuple (With a Comma!)
A single-element tuple must include a comma after the element.


single = ("hello",) # ✅ Correct
not_a_tuple = ("hello") # ❌ This is just a string

🔹 Tuple with tuple() Constructor

new_tuple = tuple([10, 20, 30]) # Convert list to tuple
print(new_tuple) # Output: (10, 20, 30)

2️⃣ Accessing Elements (Indexing & Slicing)

🔹 Indexing (Access by Position)
Tuples use zero-based indexing, just like lists.


fruits = ("apple", "banana", "cherry")

print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
print(fruits[-1]) # Output: cherry (last item)

🔹 Slicing (Extracting a Subset)
tuple[start:end:step]


numbers = (10, 20, 30, 40, 50, 60)

print(numbers[1:4]) # Output: (20, 30, 40)
print(numbers[:3]) # Output: (10, 20, 30)
print(numbers[::2]) # Output: (10, 30, 50)
print(numbers[::-1]) # Output: (60, 50, 40, 30, 20, 10) (reverse tuple)

3️⃣ Tuple Immutability (Cannot Be Modified)
Tuples cannot be changed after creation.

🔹 Trying to Modify a Tuple (❌ Error)

fruits = ("apple", "banana", "cherry")
fruits[1] = "orange" # ❌ TypeError: 'tuple' object does not support item assignment

4️⃣ Tuple Operations

🔹 Concatenation & Repetition

tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)

print(tuple1 + tuple2) # Output: (1, 2, 3, 4, 5, 6) (Concatenation)
print(tuple1 * 3) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3) (Repetition)

5️⃣ Tuple Methods

Method Description
count(item) Returns the number of occurrences of an item
index(item) Returns the index of the first occurrence

🔹 Example:

numbers = (10, 20, 10, 30, 40)

print(numbers.count(10)) # Output: 2 (10 appears twice)
print(numbers.index(30)) # Output: 3 (index of first 30)

6️⃣ Converting Between Lists & Tuples
🔹 Tuple to List (Mutable Copy)

tuple1 = (1, 2, 3)
list1 = list(tuple1) # Convert tuple to list
list1.append(4)
print(list1) # Output: [1, 2, 3, 4]
🔹 List to Tuple

list1 = [10, 20, 30]
tuple1 = tuple(list1)
print(tuple1) # Output: (10, 20, 30)

7️⃣ When to Use Tuples?

✅ When you need an immutable sequence (e.g., fixed configuration values).

✅ When you want faster performance (tuples are more memory-efficient than lists).

✅ When you need to use a tuple as a dictionary key (lists cannot be keys).


    Date: 2025-03-22 00:00:00.000000