Tuples in Python

A tuple is an ordered, immutable collection of items. Unlike lists, tuples cannot be modified after creation, making them useful for storing read-only data.


1. Creating Tuples

Tuples are defined using parentheses () and can store different data types.

Example:

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

Output:

('apple', 'banana', 'cherry') (1, 2, 3, 4, 5) ('Python', 3.14, True)

2. Accessing Tuple Elements

Tuples use zero-based indexing to access elements.

Example:

tuple1 = ("apple", "banana", "cherry")
print(tuple1[0])  # First item
print(tuple1[-1]) # Last item

Output:

apple
cherry

3. Slicing Tuples

You can extract portions of a tuple using slicing.

Example:

tuple2 = (10, 20, 30, 40, 50)
print(tuple2[1:4])  # Elements from index 1 to 3
print(tuple2[:3])   # First three elements
print(tuple2[::-1]) # Reverse tuple

4. Tuple Immutability

Tuples cannot be modified after creation.

Example:

tuple3 = ("apple", "banana", "cherry")
tuple3[1] = "orange"  # ❌ This will raise an error

To modify a tuple, convert it to a list and back to a tuple:

tuple4 = ("apple", "banana", "cherry")
temp_list = list(tuple4)
temp_list[1] = "orange"
tuple4 = tuple(temp_list)
print(tuple4)

5. Tuple Packing & Unpacking

Tuples allow packing multiple values into one variable and unpacking them into separate variables.

Example:

person = ("Alice", 25, "Engineer")  # Packing
ame, age, profession = person  # Unpacking
print(name, age, profession)

Output:

Alice 25 Engineer

6. Looping Through a Tuple

Example:

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

7. Tuple Methods

Tuples have a few built-in methods:

Example:

numbers = (1, 2, 3, 3, 4, 5)
print(numbers.count(3))  # Count occurrences of 3
print(numbers.index(4))  # Find index of 4

8. Nested Tuples

Tuples can contain other tuples.

Example:

nested_tuple = ((1, 2, 3), ("a", "b", "c"))
print(nested_tuple[0])  # Output: (1, 2, 3)
print(nested_tuple[1][1])  # Output: 'b'

9. Converting Between Lists and Tuples

Convert lists to tuples and vice versa:

Example:

list1 = [1, 2, 3]
tuple1 = tuple(list1)
print(tuple1)

tuple2 = ("a", "b", "c")
list2 = list(tuple2)
print(list2)

10. Summary

Tuples are immutable ordered collections of elements.
Access tuple elements using indexing and slicing.
Packing & unpacking tuples is a useful feature.
Looping & built-in methods allow easy tuple manipulation.
Tuples are faster than lists and useful for read-only data.

Leave a Reply

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

Scroll to Top