Write a python program to convert a list to tuple using tuple function

1. Introduction

In this blog post, we will write a Python program to convert a list into a tuple using the tuple() function. This conversion is a common task in Python, as it allows us to switch between mutable and immutable data types, depending on the requirements of our program.

2. Program Steps

1. Define a list with some elements.

2. Use the tuple() function to convert the list into a tuple.

3. Return or print the tuple.

3. Code Program


def convert_list_to_tuple(input_list):
    # Step 2: Convert the list to a tuple
    output_tuple = tuple(input_list)

    # Step 3: Return the tuple
    return output_tuple

# Step 1: Define a list
original_list = [1, 2, 3, 4, 5]
converted_tuple = convert_list_to_tuple(original_list)
print("Converted Tuple:", converted_tuple)

Output:

For the original list [1, 2, 3, 4, 5], the output will be:
Converted Tuple: (1, 2, 3, 4, 5)

Explanation:

1. The function convert_list_to_tuple is defined to accept a list, input_list, as its parameter.

2. Inside the function, the tuple() function is called with input_list as an argument. This function takes an iterable (in this case, the list) and converts it into a tuple.

3. The new tuple, output_tuple, is then returned. When the function is called with the list [1, 2, 3, 4, 5], it returns a tuple (1, 2, 3, 4, 5).

4. Converting a list to a tuple is useful when a non-modifiable (immutable) version of the list is needed. Tuples are faster and consume less memory compared to lists, making them preferable in scenarios where data integrity and performance are key.

This program shows a straightforward way to convert a list to a tuple in Python, demonstrating how to work with different types of collections and their properties.


Comments