Python – Type conversion in Nested and Mixed List

While working with Python lists, due to its heterogenous nature, we can have a problem in which we need to convert data type of each nested element of list to particular type. In mixed list, this becomes complex. Let’s discuss certain way in which this task can be performed.

Input : test_list = [(‘7’, [‘8’, (‘5’, )])]
Output : [(7, [8, (5, )])]

Input : test_list = [‘6’]
Output : [6]

Method : 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

The original list is : ['6', '89', ('7', ['8', '10']), ['11', '15']]
Data after type conversion : [6, 89, (7, [8, 10]), [11, 15]]
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.