Monday, November 18, 2024
Google search engine
HomeLanguagesPython – Type conversion in Nested and Mixed List

Python – Type conversion in Nested and Mixed List

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))


Output

The 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))


Output

The 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.

  1. Initialize a stack with the input list.
  2. While the stack is not empty, pop the top element of the stack and assign it to the variable current_list.
  3. For each element in the current_list, check if the element is a list.
  4. If it is a list, append it to the stack.
  5. If it is not a list, check if it is a string. If it is a string, convert it to the target type.
  6. Repeat steps 3-5 until the stack is empty.
  7. 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)))


Output

The 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:

  1. 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.
  2. If the input is a list or tuple, it calls itself recursively on each element and returns the list of converted elements.
  3. If the input is a string that represents an integer, it returns the integer equivalent.
  4. Otherwise, it returns the input element as-is.
  5. The main program initializes a test list and calls the change_type function on it.
  6. 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))


Output

The 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:

  1. Initialize an empty queue and enqueue the input list.
  2. Create an empty result list.
  3. 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.
  4. 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))


Output

The 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

  1. Define an empty stack and push the input list into it.
  2. Define an empty result list.
  3. 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.
  4. 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))


Output

The 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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments