How to Create and Use Tuples in Python

1. Introduction

Tuples are one of the four built-in data types in Python used to store collections of data. They are similar to lists in that they can hold a collection of items. However, unlike lists, tuples are immutable, which means once a tuple is created, its contents cannot be altered. This immutability makes tuples a bit faster than lists and suitable for read-only collections of items.

Definition

A tuple is a collection that is ordered and immutable. Tuples are written with round brackets and can contain mixed data types. They are indexed, support duplicate elements, and can be nested. The immutability of tuples makes them a valid key in a dictionary.

2. Program Steps

1. Create a tuple with different data types.

2. Access elements in a tuple.

3. Attempt to change an element in the tuple to demonstrate immutability.

4. Use tuple unpacking to assign values to variables.

5. Iterate through a tuple using a for loop.

3. Code Program

# Step 1: Create a tuple with different data types
my_tuple = (1, "Hello", 3.14)

# Step 2: Access elements in the tuple
first_element = my_tuple[0]

# Step 3: Print the first element
print("First element:", first_element)

# Step 4: Attempt to change an element in the tuple (this should raise an error)
try:
    my_tuple[0] = 2
except TypeError as e:
    print(e)

# Step 5: Use tuple unpacking to assign values to variables
(number, string, pi) = my_tuple

# Step 6: Print the variables to verify tuple unpacking
print("Number:", number)
print("String:", string)
print("Pi:", pi)

# Step 7: Iterate through the tuple using a for loop
for item in my_tuple:
    print(item)

Output:

First element: 1
'tuple' object does not support item assignment
Number: 1
String: Hello
Pi: 3.14
1
Hello
3.14

Explanation:

1. my_tuple is created with an integer, a string, and a float.

2. first_element is assigned the value at index 0 of my_tuple, which is 1.

3. Attempting to change the value at index 0 of my_tuple results in a TypeError because tuples are immutable.

4. Tuple unpacking is demonstrated, with number, string, and pi being assigned the respective values from my_tuple.

5. The variables number, string, and pi are printed, showing the values obtained through tuple unpacking.

6. A for loop is used to iterate over my_tuple, printing each item.

7. The output confirms the contents of the tuple and the result of attempting to modify it.

Comments