Python - Tuples

13.
What is the purpose of the len() function when applied to tuples?

The len() function in Python is used to determine the number of elements in a tuple. It returns the length or the number of items in the specified tuple. Let's explore its usage with an example program:

# Creating a tuple
my_tuple = (10, 20, 30, 40, 50)

# Using len() to get the length of the tuple
tuple_length = len(my_tuple)

# Displaying the result
print(f"The length of the tuple is: {tuple_length}")

In this program, we create a tuple (my_tuple) and then use the len() function to determine the length of the tuple. The result is the number of elements in the tuple.

Output:

The length of the tuple is: 5

14.
How do you convert a tuple into a list and vice versa in Python?

In Python, you can convert a tuple into a list using the list() constructor, and vice versa, you can convert a list into a tuple using the tuple() constructor. Let's see examples of both conversions:

# Convert a tuple to a list
my_tuple = (1, 2, 3, 4, 5)
my_list = list(my_tuple)

# Display the result
print("Tuple:", my_tuple)
print("List:", my_list)
# Convert a list to a tuple
my_list = [1, 2, 3, 4, 5]
my_tuple = tuple(my_list)

# Display the result
print("List:", my_list)
print("Tuple:", my_tuple)

These examples demonstrate the use of list() to convert a tuple to a list and tuple() to convert a list to a tuple.

Tuple: (1, 2, 3, 4, 5)
List: [1, 2, 3, 4, 5]

List: [1, 2, 3, 4, 5]
Tuple: (1, 2, 3, 4, 5)

15.
Discuss the role of the index() method in Python tuples.

The index() method in Python tuples is used to find the index of the first occurrence of a specified element. It takes the value to search for as an argument and returns the index of the first occurrence of that value.

# Creating a tuple
my_tuple = (10, 20, 30, 20, 40, 50)

# Using the index() method to find the index of 20
index_of_20 = my_tuple.index(20)

# Displaying the result
print(f"The index of the first occurrence of 20 is: {index_of_20}")

In this example, we create a tuple (my_tuple) and then use the index() method to find the index of the first occurrence of the value 20. The result is the index of the first occurrence.

Output:

The index of the first occurrence of 20 is: 1

16.
What is the significance of parentheses in tuple creation?

In Python, parentheses are used to create tuples. The significance of parentheses in tuple creation is to denote a sequence of elements enclosed within them as a tuple. Let's see an example to illustrate this:

# Creating a tuple with parentheses
my_tuple = (1, 2, 3, 4, 5)

# Displaying the result
print("Tuple:", my_tuple)

In this example, we use parentheses to create a tuple (my_tuple) containing the elements 1, 2, 3, 4, and 5.

Output:

Tuple: (1, 2, 3, 4, 5)