Friday, November 1, 2024
Google search engine
HomeLanguagesPython | Type casting whole List and Matrix

Python | Type casting whole List and Matrix

Sometimes, while working with Python List or Matrix, we usually have a problem in which we require to get a generalized function which could perform the type casting of whole container at once. There is always a need of a mechanism code which can transform entirely the allowed change of data type for all elements in container. Let’s discuss a way in which this task can be performed. 

Method : Using map() + list comprehension This task can be performed using a map(). The transformation of a normal list can be performed using a single map function by just passing the desired data type. But when it comes to transformation of whole matrix, we need the help of list comprehension for the same. 

Python3




# Python3 code to demonstrate working of
# Type casting whole List and Matrix
# using map() + list comprehension
 
# helper function to type cast list
def cast_list(test_list, data_type):
    return list(map(data_type, test_list))
     
# helper function to type cast Matrix
def cast_matrix(test_matrix, data_type):
    return list(map(lambda sub: list(map(data_type, sub)), test_matrix))
     
# initialize list
test_list = [1, 4, 9, 10, 19]
 
# initialize Matrix
test_matrix = [[5, 6, 8], [8, 5, 3], [9, 10, 3]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# printing original matrix
print("The original Matrix is : " + str(test_matrix))
 
# Type casting whole List and Matrix
# using map() + list comprehension
res_list = cast_list(test_list, str)
res_matrix = cast_matrix(test_matrix, str)
 
# printing result
print("The List after type casting is : " + str(res_list))
print("The Matrix after type casting is : " + str(res_matrix))


Output : 

The original list is : [1, 4, 9, 10, 19]
The original Matrix is : [[5, 6, 8], [8, 5, 3], [9, 10, 3]]
The List after type casting is : ['1', '4', '9', '10', '19']
The Matrix after type casting is : [['5', '6', '8'], ['8', '5', '3'], ['9', '10', '3']]

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.  
Auxiliary Space: O(n), where n is the number of elements in the new res list 

Method #2: Using numpy library

Note: Install numpy module using command “pip install numpy”

This task can also be performed using numpy library which provides an inbuilt function to change the data type of entire matrix or array.

Python3




import numpy as np
 
# initialize list
test_list = [1, 4, 9, 10, 19]
   
# initialize Matrix
test_matrix = [[5, 6, 8], [8, 5, 3], [9, 10, 3]]
   
# printing original list
print("The original list is : " + str(test_list))
   
# printing original matrix
print("The original Matrix is : " + str(test_matrix))
   
# Type casting whole List and Matrix
# using numpy library
res_list = np.array(test_list, dtype=str)
res_matrix = np.array(test_matrix, dtype=str)
   
# printing result
print("The List after type casting is : " + str(res_list))
print("The Matrix after type casting is : " + str(res_matrix))
#This code is contributed by Edula Vinay Kumar Reddy


Output:

The original list is : [1, 4, 9, 10, 19]
The original Matrix is : [[5, 6, 8], [8, 5, 3], [9, 10, 3]]
The List after type casting is : [‘1’ ‘4’ ‘9’ ’10’ ’19’]
The Matrix after type casting is : [[‘5’ ‘6’ ‘8’]
[‘8’ ‘5’ ‘3’]
[‘9′ ’10’ ‘3’]]

Time complexity: O(n)

Auxiliary Space: O(n) where n is number of all elements in array.

Method 3 : Use a loop

step-by-step approach:

  1. Define a function cast_list_loop that takes a list test_list and a data type data_type as arguments, and returns a new list where each element is of the specified data type.
  2. Initialize an empty list res_list to store the results.
  3. Use a loop to iterate over the elements of test_list.
  4. Convert each element to the desired data type using the data_type function, and append the result to res_list.
  5. Return res_list.
  6. Define a function cast_matrix_loop that takes a matrix test_matrix and a data type data_type as arguments, and returns a new matrix where each element is of the specified data type.
  7. Initialize an empty list res_matrix to store the results.
  8. Use two nested loops to iterate over the sublists of test_matrix.
  9. Convert each element to the desired data type using the data_type function, and append the result to a new list row.
  10. Append row to res_matrix.
  11. Return res_matrix.

Python3




def cast_list_loop(test_list, data_type):
    res_list = []
    for item in test_list:
        res_list.append(data_type(item))
    return res_list
 
def cast_matrix_loop(test_matrix, data_type):
    res_matrix = []
    for row in test_matrix:
        res_row = []
        for item in row:
            res_row.append(data_type(item))
        res_matrix.append(res_row)
    return res_matrix
 
# initialize list
test_list = [1, 4, 9, 10, 19]
 
# initialize Matrix
test_matrix = [[5, 6, 8], [8, 5, 3], [9, 10, 3]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# printing original matrix
print("The original Matrix is : " + str(test_matrix))
 
# Type casting whole List and Matrix using loop
res_list = cast_list_loop(test_list, str)
res_matrix = cast_matrix_loop(test_matrix, str)
 
# printing result
print("The List after type casting is : " + str(res_list))
print("The Matrix after type casting is : " + str(res_matrix))


Output

The original list is : [1, 4, 9, 10, 19]
The original Matrix is : [[5, 6, 8], [8, 5, 3], [9, 10, 3]]
The List after type casting is : ['1', '4', '9', '10', '19']
The Matrix after type casting is : [['5', '6', '8'], ['8', '5', '3'], ['9', '10', '3']]

The time complexity of the loop-based approach is O(n) for the list and O(mn) for the matrix, where n is the length of the list and m is the number of rows in the matrix. 

The auxiliary space is O(n) for the list and O(mn) for the matrix, since we create new lists to store the results.

RELATED ARTICLES

Most Popular

Recent Comments