In this tutorial, we will be discussing the method to convert a List to a Tuple in Python.
Often, while developing software in Python, we come across scenarios where we need to convert a list to a tuple for execution as the latter has advantages like faster execution and being immutable.
Hence, knowing how to convert a list to a tuple can prove to be an important skill in Python programming.
Step 1: Defining a List
Initiate the process by defining a list. A list in Python is a collection of items that are changeable and kept in a certain order. Lists are written with square brackets. For instance:
1 |
my_list = ['apple', 'banana', 'cherry'] |
Step 2: Convert the List to Tuple
A tuple in Python is similar to a list. The difference between the two is that tuples are immutable, which means that we cannot change the elements of a tuple once it is assigned whereas in a list, elements can be changed.
To convert a list to a tuple we make use of the tuple() function.
1 |
converted_tuple = tuple(my_list) |
This will convert your list, my_list, into a tuple, converted_tuple.
Step 3: Verification of Conversion
To be certain that the conversion took place without any issues, print the converted tuple.
1 |
print(converted_tuple) |
('apple', 'banana', 'cherry')
Full code:
1 2 3 4 5 6 7 8 |
# Defining list my_list = ['apple', 'banana', 'cherry'] # Converting list to tuple converted_tuple = tuple(my_list) # Printing the tuple print(converted_tuple) |
Conclusion
Converting a list to a tuple in Python is a simple process and very useful especially when we need an immutable collection of items.
The tuple() function is a built-in Python function specifically designed to convert a list to a tuple which makes it extremely convenient and efficient.
Don’t forget to verify the conversion by printing the converted tuple. This ensures that the conversions are executed as required.