How to Convert Python Lists to Tuples

In this Python Lists we want to talk about How to Convert Python Lists to Tuples, Python is  powerful programming language that provides developers with different builtin data structures. two commonly used data structures in Python are tuples and lists. while tuples are immutable and ordered sequences of elements, lists are mutable and can be changed as needed. in this article we want to discuss how to convert tuples to lists in Python.

 

For converting a list to a tuple we can use the builtin tuple() function. tuple() function takes any iterable object as input and returns a tuple containing all the elements of the iterable object.

 

This is an example of how to convert list to tuple

In this example we have defined a list called my_list with five elements. after that we have converted the list to a tuple using the tuple() function and assign the result to a variable called my_tuple. and lastly we print the contents of the tuple using the print() function.

 

 

This will be the result

How to Convert Python Lists to Tuples
How to Convert Lists to Tuples

 

 

If we have a list that contains other lists we can convert nested lists to nested tuples using  list comprehension. Alist comprehension is a way to create new list based on an existing iterable object.

This is an example of how to convert nested lists to nested tuples using list comprehension

In this example we have defined nested list called nested_list that contains three lists with two elements each. after that we have used a list comprehension to convert each nested list to nested tuple and assign the result to a variable called nested_tuple. and lastly we print the contents of the nested tuple using the print() function.

 

 

This will be the result

How to Convert Python Lists to Tuples
How to Convert Python Lists to Tuples

 

 

Learn More on Python Tuples

Leave a Comment