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
1 2 3 4 5 6 7 8 |
# Define a list my_list = [1, 2, 3, 4, 5] # Convert the list to a tuple my_tuple = tuple(my_list) # Print the tuple print(my_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
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
1 2 3 4 5 6 7 8 |
# Define a nested list nested_list = [[1, 2], [3, 4], [5, 6]] # Convert the nested list to a nested tuple nested_tuple = tuple(tuple(l) for l in nested_list) # Print the nested tuple print(nested_tuple) |
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