![]() |
VOOZH | about |
Sometimes we deal with different types of data types and we require to inter-convert from one data type to another hence interconversion is always a useful tool to have knowledge. This article deals with the converse case. Let's discuss certain ways in which this can be done in Python.
In this method, we simply use the tuple() method to convert the list into a tuple.
Output:
[('Geeks', 'For', 'Geeks')]
<class 'list'>In this method, we are using the asterisk operator for dereferencing it to convert a list of strings to a list of tuples.
Output:
[('Geeks', 'For', 'Geeks')]
<class 'list'>This task can be achieved using the combination of these functions. The map function can be used to link the logic to each string, the split function is used to split the inner contents of the list into different tuple attributes and the tuple function performs the task of forming a tuple.
Output :
The original list : ['4, 1', '3, 2', '5, 3'] The list after conversion to tuple list : [(4, 1), (3, 2), (5, 3)]
This is the most elegant way to perform this particular task. Where the map function is used to extend the function logic to the whole list eval function internally performs interconversions and splitting.
Output:
The original list : ['4, 1', '3, 2', '5, 3'] The list after conversion to tuple list : [(4, 1), (3, 2), (5, 3)]
Algorithm:
Import the ast module.
Initialize a list of strings that needs to be converted into tuples.
Print the original list.
Use ast.literal_eval() function to convert each string in the list into a tuple of integers.
Store each tuple in a new list called res.
Print the list after conversion to tuple list.
The original list : ['4, 1', '3, 2', '5, 3'] The list after conversion to tuple list : [(4, 1), (3, 2), (5, 3)]
The time complexity of this code is O(n), where n is the number of strings in the input list. The space complexity is also O(n), since we create a new list of tuples with the same length as the input list.
Method 9: Using the __iadd__ method and a list containing the tuple.
Algorithm:
The original list : ['4, 1', '3, 2', '5, 3']
The list after conversion to tuple list : [('4, 1', '3, 2', '5, 3')]
Time complexity:
The time complexity of this implementation depends on the length of the input list of strings. Converting a list to a tuple has a time complexity of O(n), where n is the length of the list. Appending a tuple to a list using the __iadd__ method has a time complexity of O(1). Therefore, the overall time complexity of this implementation is O(n).
Space complexity:
The space complexity of this implementation also depends on the length of the input list of strings. Converting a list to a tuple requires additional memory and has a space complexity of O(n), where n is the length of the list. Appending the tuple to the list li using the __iadd__ method does not create a new list and has a space complexity of O(1). Therefore, the overall space complexity of this implementation is O(n).