Open In App

Python – Change Datatype of Tuple Values

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with set of records, we can have a problem in which we need to perform a data type change of values of tuples, which are in its 2nd position, i.e value position. This kind of problem can occur in all domains that include data manipulations. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [(44, 5.6), (16, 10)]
Output : [(44, '5.6'), (16, '10')]

Input : test_list = [(44, 5.8)]
Output : [(44, '5.8')]

Method #1 : Using enumerate() + loop This is brute force way in which this problem can be solved. In this, we reassign the tuple values, by changing required index of tuple to type cast using appropriate datatype conversion functions. 

Python3




# Python3 code to demonstrate working of
# Change Datatype of Tuple Values
# Using enumerate() + loop
 
# initializing list
test_list = [(4, 5), (6, 7), (1, 4), (8, 10)]
 
# printing original list
print("The original list is :"
       + str(test_list))
 
# Change Datatype of Tuple Values
# Using enumerate() + loop
# converting to string using str()
for idx, (x, y) in enumerate(test_list):
    test_list[idx] = (x, str(y))
 
# printing result
print("The converted records :"
       + str(test_list))


Output

The original list is :[(4, 5), (6, 7), (1, 4), (8, 10)]
The converted records :[(4, '5'), (6, '7'), (1, '4'), (8, '10')]

Time Complexity: O(n2) 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 list “test_list”. 

Method #2 : Using list comprehension The above functionality can also be used to solve this problem. In this, we perform similar task as above method, just in one liner way using list comprehension. 

Python3




# Python3 code to demonstrate working of
# Change Datatype of Tuple Values
# Using list comprehension
 
# initializing list
test_list = [(4, 5), (6, 7), (1, 4), (8, 10)]
 
# printing original list
print("The original list is :"
       + str(test_list))
 
# Change Datatype of Tuple Values
# Using list comprehension
# converting to string using str()
res = [(x, str(y)) for x, y in test_list]
 
# printing result
print("The converted records :"
       + str(res))


Output

The original list is :[(4, 5), (6, 7), (1, 4), (8, 10)]
The converted records :[(4, '5'), (6, '7'), (1, '4'), (8, '10')]

Time Complexity: O(n*n) where n is the number of elements in the in the list “test_list”. The list comprehension is used to perform the task and it takes O(n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the in the list “test_list”.



Last Updated : 13 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads