Python - Type conversion in Nested and Mixed List


Python is widely used and accepted today because of its versatility and readability. Its powerful features allow developers to perform complex tasks with ease. One such essential feature is type conversion or type casting. Especially with Python lists, which are heterogeneous in nature which often demands converting each nested list element or lists to be converted to a particular data type for use. In mixed lists, it becomes more complex.

In this article, we will try to understand and implement type conversion in Nested and Mixed Lists. Through the codes we will decode the python features to implement the same.

Before we start with lists, we need to understand type conversion or type casting. Type casting in python refers to converting the data type of a value or variable as per convenience or feasibility. Python has several built in functions to facilitate type conversion, those prove to be very useful when it comes to nested and mixed lists.

Nested and Mixed Lists

When a list is contained inside another list it is termed as a nested list. These nested lists can contain more nested lists inside them as elements following a hierarchical order. When working with nested lists especially in type conversion it is necessary to understand how the type conversion will affect the entire structure.

Mixed lists upholds the heterogeneous nature of Python lists. It is a list that holds elements of different data types, such as integers, floats, lists, tuples, etc. Dealing with type conversions in mixed lists requires a slightly different approach. We need to handle each element independently and convert it to the desired type.

Type conversion in nested and mixed lists is converting the elements in the sub-lists or tuples or any iterable so as to preserve the original structure of the overall list. Now, let us look into some of the methods one by one.

Method #1: List Comprehension

List comprehension is a very easy and elegant way for type conversion of elements in a nested list. It allows us to create a new nested list iterating through each element and applying required type conversion operations.

Example

listEnter = [6, 5, [1,2], 3]
print("List entered: "+ str(listEnter))

result = [[str(ele) for ele in sublist] if isinstance(sublist, list) else str(sublist) for sublist in listEnter]
print("After conversion: "+ str(result))

Output

List entered: [6, 5, [1, 2], 3]
After conversion: ['6', '5', ['1', '2'], '3']

So we have used a statement, where each element from the sub-list is iterated if it is part of the main list and converted to string. Else takes the element from the main list and converts to String. In this way, the original structure is retained but the individual elements get converted.

Method #2: Using Recursion

Recursion or using a for loop, iterating through each element and explicitly converting it as per our requirement. A function can be defined that will iterate and convert the elements. Amidst we need to check if there are inner lists or tuples or other iterables, wherein we can call the function again recursively to iterate each nested list or tuples,etc incase of a mixed list to convert each element inside them. So we will write the code and understand.

Example

def typeCast(listInput):
    if isinstance(listInput, list):
        return [typeCast(inputItem) for inputItem in listInput]
    else:
        return str(listInput)

listEnter = [6, 5, [1,2], 3]
print("List entered: "+ str(listEnter))

result = typeCast(listEnter)
print("After conversion: "+ str(result))

Output

List entered: [6, 5, [1, 2], 3]
After conversion: ['6', '5', ['1', '2'], '3']

So clearly the typeCast() recursive function iterates through each element of the list. When the element is a list itself then the function passes the list in itself. Otherwise, it converts its element to a String.

And the process goes on. After understanding the recursion implementation in nested lists. Let us check the possible way to use it in a mixed list.

Example

def typeCast(inputEle):
    if isinstance(inputEle, list):
        return [typeCast(ele) for ele in inputEle]
    elif isinstance(inputEle, tuple):
        return tuple(typeCast(ele) for ele in inputEle)
    else:
        return int(inputEle)

def typeCast2(inputEle):
    if type(inputEle) is list:
        return [typeCast2(ele) for ele in inputEle]
    elif type(inputEle) is tuple:
        return tuple(typeCast2(ele) for ele in inputEle)
    else:
        return int(inputEle)

listInput = ['1', '2', ('3', ['4', '5']), ['6', '7']]
print("Input list is: " + str(listInput))

res1 = typeCast(listInput)
print("Using isinstance() converted: " + str(res1))

res2 = typeCast2(listInput)
print("Using type() converted: " + str(res2))

Output

Input list is: ['1', '2', ('3', ['4', '5']), ['6', '7']]
Using isinstance() converted: [1, 2, (3, [4, 5]), [6, 7]]
Using type() converted: [1, 2, (3, [4, 5]), [6, 7]]

In this code we see the similar implementation with isinstance() function and iterating through each element checking for several data types. If matched, recall the function again passing the data, else convert the element to integer.

Also along with that a second approach of using type() instead of isinstance(), that gives us the same output. In python, isinstance() is used to check whether the object is of a specific data type, else returns false. Whereas, type() on the other hand is mostly useful in debugging. When a single argument is passed it returns the type of the object.

Both have the same time and space complexity hence its use is relevant as per convenience.

Method #3: Implementing map and lambda

The map() function in python allows us to apply a specified function to each element in a list or other iterable. It takes in two arguments the iterable and the function. Let us use it with the lambda function to type cast each element in a mixed list.

Example

def typeCast(inputEle):
    return list(map(lambda x: typeCast(x) if isinstance(x, (list, tuple)) else int(x), inputEle))

listInput = ['1', '2', ('3', ['4', '5']), ['6', '7']]
print("Input list is: " + str(listInput))

res = typeCast(listInput)
print("After conversion: " + str(res))

Output

Input list is: ['1', '2', ('3', ['4', '5']), ['6', '7']]
After conversion: [1, 2, (3, [4, 5]), [6, 7]]

So we see how efficient the map function is; it makes each element in the list iterate through a function as defined in the lambda. The lambda function checks if each element is either a list or a tuple using isinstance() and recursively calling back the typecast() function into effect for each nested list or tuple inside the list. Else it converts it into an integer. Thus this way each element gets iterated and converted into an integer.

The map function then processes each element of the input list using this lambda function and returns an iterator. We convert the returned iterator back into a list using the list() function.

Conclusion

In this article, we have tried to create an understanding of Nested and Mixed lists and how to type cast the data in them. We learned type conversion or type casting helps us change the data type according to our requirements, which is very useful when it comes to complex data structures. We have discussed three useful methods that we can implement in Nested and Mixed lists to achieve the same.

Understanding type conversion is a crucial skill for Python developers, as it helps us to efficiently manipulate data and also ensures proper functioning of our programs. With this we also leave behind other scopes of implementing the same. Try and explore.

Updated on: 29-Aug-2023

107 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements