Python - Type conversion in Nested and Mixed List
Last Updated :
04 Apr, 2023
While working with Python lists, due to its heterogeneous nature, we can have a problem in which we need to convert the data type of each nested element of list to a particular type. In mixed list, this becomes complex. Let's discuss the certain ways in which this task can be performed.
Input : test_list = [('7', ['8', ('5', )])]
Output : [(7, [8, (5, )])]
Input : test_list = ['6']
Output : [6]
Method 1: Using recursion + isinstance()
The combination of above functions can be used to solve this problem. In this, we use isinstance() to get the data type of element of list, and if its container, the inner elements are recursed to perform conversion.
Python3
# Python3 code to demonstrate working of
# Type conversion in Nested and Mixed List
# Using recursion + isinstance()
# helper_fnc
def change_type(sub):
if isinstance(sub, list):
return [change_type(ele) for ele in sub]
elif isinstance(sub, tuple):
return tuple(change_type(ele) for ele in sub)
else:
return int(sub)
# initializing list
test_list = ['6', '89', ('7', ['8', '10']), ['11', '15']]
# printing original list
print("The original list is : " + str(test_list))
# Type conversion in Nested and Mixed List
# Using recursion + isinstance()
res = change_type(test_list)
# printing result
print("Data after type conversion : " + str(res))
OutputThe original list is : ['6', '89', ('7', ['8', '10']), ['11', '15']]
Data after type conversion : [6, 89, (7, [8, 10]), [11, 15]]
Time Complexity: O(n), where n is the total number of elements in the nested list.
Auxiliary Space: O(d) where d is the maximum depth of the nested list. This is because the program uses recursion and at each level of recursion, a new function call is added to the call stack, which takes up a constant amount of space. The maximum number of function calls on the call stack at any one time is equal to the maximum depth of the nested list.
Method 2: Using recursion + type() method
Python3
# Python3 code to demonstrate working of
# Type conversion in Nested and Mixed List
def change_type(sub):
if type(sub) is list:
return [change_type(ele) for ele in sub]
elif type(sub) is tuple:
return tuple(change_type(ele) for ele in sub)
else:
return int(sub)
# initializing list
test_list = ['6', '89', ('7', ['8', '10']), ['11', '15']]
# printing original list
print("The original list is : " + str(test_list))
# Type conversion in Nested and Mixed List
res = change_type(test_list)
# printing result
print("Data after type conversion : " + str(res))
OutputThe original list is : ['6', '89', ('7', ['8', '10']), ['11', '15']]
Data after type conversion : [6, 89, (7, [8, 10]), [11, 15]]
Time Complexity : O(N)
Auxiliary Space : O(1)
Method 3: A stack-based approach to traverse the nested elements in the input list.
- Initialize a stack with the input list.
- While the stack is not empty, pop the top element of the stack and assign it to the variable current_list.
- For each element in the current_list, check if the element is a list.
- If it is a list, append it to the stack.
- If it is not a list, check if it is a string. If it is a string, convert it to the target type.
- Repeat steps 3-5 until the stack is empty.
- Return the input list.
Python3
def convert_elements_v2(input_list, target_type):
stack = [input_list]
while stack:
current_list = stack.pop()
for i in range(len(current_list)):
if isinstance(current_list[i], list):
stack.append(current_list[i])
else:
current_list[i] = target_type(current_list[i]) if isinstance(
current_list[i], str) else current_list[i]
return input_list
test_list = ['6', '89', ('7', ['8', '10']), ['11', '15']]
# printing original list
print("The original list is : " + str(test_list))
# printing result
print("Data after type conversion : " +
str(convert_elements_v2(test_list, int)))
OutputThe original list is : ['6', '89', ('7', ['8', '10']), ['11', '15']]
Data after type conversion : [6, 89, ('7', ['8', '10']), [11, 15]]
Time complexity: O(n), where n is the number of elements in the input list, including nested elements. This is because each element is visited once and the operations performed on each element take constant time.
Auxiliary space: O(d), where d is the maximum depth of the nested elements in the input list. This is because the stack stores the nested elements, and the maximum size of the stack is equal to the maximum depth of the nested elements.
Method 4: Using map() and lambda function
Algorithm:
- The change_type function takes a list as input and returns a list with the same elements but with all strings that represent integers converted to integers.
- If the input is a list or tuple, it calls itself recursively on each element and returns the list of converted elements.
- If the input is a string that represents an integer, it returns the integer equivalent.
- Otherwise, it returns the input element as-is.
- The main program initializes a test list and calls the change_type function on it.
- The output is printed to the console.
Python3
# Python3 code to demonstrate working of
# Type conversion in Nested and Mixed List
def change_type(lst):
return list(map(lambda x: change_type(x) if type(x) in [list, tuple] else int(x), lst))
# initializing list
test_list = ['6', '89', ('7', ['8', '10']), ['11', '15']]
# printing original list
print("The original list is : " + str(test_list))
# Type conversion in Nested and Mixed List
res = change_type(test_list)
# printing result
print("Data after type conversion : " + str(res))
OutputThe original list is : ['6', '89', ('7', ['8', '10']), ['11', '15']]
Data after type conversion : [6, 89, ('7', ['8', '10']), [11, 15]]
Time complexity: O(n), where n is the total number of elements in the input list. This is because each element in the list is processed exactly once.
Auxiliary Space: O(n), where n is the total number of elements in the input list. This is because the function creates a new list to hold the converted elements.
Method 5: Using queue to traverse the nested elements in the input list.
Approach:
- Initialize an empty queue and enqueue the input list.
- Create an empty result list.
- Loop until the queue is not empty:
a. Dequeue the next element from the queue.
b. If the element is a list or tuple, enqueue each element of the list or tuple.
c. If the element is not a list or tuple, convert it to an integer and append it to the result list. - Return the result list.
Python3
def change_type(lst):
queue = [lst]
res = []
while queue:
curr = queue.pop(0)
if isinstance(curr, (list, tuple)):
for x in curr:
queue.append(x)
else:
res.append(int(curr))
return res
# initializing list
test_list = ['6', '89', ('7', ['8', 10]), ['11', 15]]
# printing original list
print("The original list is : " + str(test_list))
# Type conversion in Nested and Mixed List
res = change_type(test_list)
# printing result
print("Data after type conversion : " + str(res))
OutputThe original list is : ['6', '89', ('7', ['8', 10]), ['11', 15]]
Data after type conversion : [6, 89, 7, 11, 15, 8, 10]
Time complexity: O(n), where n is the total number of elements in the input list.
Auxiliary space: O(n), where n is the total number of elements in the input list.
Method 6: Using Iterative approach with stack
- Define an empty stack and push the input list into it.
- Define an empty result list.
- While the stack is not empty, do the following:
a. Pop the last element from the stack.
b. If the popped element is a list, push all its elements into the stack.
c. If the popped element is a tuple, convert all its elements into the desired type and create a new tuple.
d. If the popped element is not a list or a tuple, convert it into the desired type.
e. Append the converted element to the result list. - Return the result list.
Python3
def change_type_iter(sub):
stack = [sub]
result = []
while stack:
current = stack.pop()
if type(current) is list:
stack.extend(current)
elif type(current) is tuple:
new_tuple = tuple(change_type_iter(ele) for ele in current)
result.append(new_tuple)
else:
result.append(int(current))
return result
# initializing list
test_list = ['6', '89', ('7', ['8', '10']), ['11', '15']]
# printing original list
print("The original list is : " + str(test_list))
# Type conversion in Nested and Mixed List
res = change_type_iter(test_list)
# printing result
print("Data after type conversion : " + str(res))
OutputThe original list is : ['6', '89', ('7', ['8', '10']), ['11', '15']]
Data after type conversion : [15, 11, ([7], [10, 8]), 89, 6]
Time complexity: O(n), where n is the total number of elements in the input list.
Auxiliary space: O(n), where n is the total number of elements in the input list.
Similar Reads
Convert Nested Dictionary to List in Python
In this article, weâll explore several methods to Convert Nested Dictionaries to a List in Python. List comprehension is the fastest and most concise way to convert a nested dictionary into a list.Pythona = { "a": {"x": 1, "y": 2}, "b": {"x": 3, "y": 4}, } # Convert nested dictionary to a list of li
3 min read
Python | Convert given list into nested list
Sometimes, we come across data that is in string format in a list and it is required to convert it into a list of the list. This kind of problem of converting a list of strings to a nested list is quite common in web development. Let's discuss certain ways in which this can be performed. Convert the
4 min read
Python | Convert a nested list into a flat list
In this article, we will cover how to Flatten a List of Lists in python. To convert a nested list into a flat list we are going to see some examples. Example: Input : l = [1, 2, [3, 4, [5, 6] ], 7, 8, [9, [10] ] ] Output : l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Input : l = [[['item1', 'item2']], [['ite
5 min read
Python - Convert a list into tuple of lists
When working with data structures in Python, there are times when we need to convert a list into a tuple of smaller lists.For example, given a list [1, 2, 3, 4, 5, 6], we may want to split it into a tuple of two lists like ([1, 2, 3], [4, 5, 6]). We will explore different methods to achieve this con
3 min read
Python | Pair and combine nested list to tuple list
Sometimes we need to convert between the data types, primarily due to the reason of feeding them to some function or output. This article solves a very particular problem of pairing like indices in list of lists and then construction of list of tuples of those pairs. Let's discuss how to achieve the
10 min read
Convert set into a list in Python
In Python, sets are unordered collections of unique elements. While they're great for membership tests and eliminating duplicates, sometimes you may need to convert a set into a list to perform operations like indexing, slicing, or sorting. For example, if input set is {1, 2, 3, 4} then Output shoul
3 min read
Python | Convert list of tuples into list
In Python we often need to convert a list of tuples into a flat list, especially when we work with datasets or nested structures. In this article, we will explore various methods to Convert a list of tuples into a list. Using itertools.chain() itertools.chain() is the most efficient way to flatten a
3 min read
Python | Type conversion of dictionary items
The interconversion of data types is quite common, and we may have this problem while working with dictionaries as well. We might have a key and corresponding list with numeric alphabets, and we with to transform the whole dictionary to integers rather than string numerics. Let's discuss certain way
6 min read
Python | Convert numeric String to integers in mixed List
Sometimes, while working with data, we can have a problem in which we receive mixed data and need to convert the integer elements in form of strings to integers. This kind of operation might be required in data preprocessing step. Let's discuss certain ways in which this task can be performed. Metho
11 min read
Type Casting Whole List and Matrix - Python
The task of type casting a whole list and matrix in Python involves converting all elements of a list or a matrix to a specific data type while preserving the structure. Given a list or matrix of integers, the goal is to transform each element into another data type, such as a string or float, effic
3 min read