When it is required to convert elements of a list of tuple into float values, the ‘isalpha’ method can be used to check if an element is an alphabet or not. The ‘float’ method is used to convert the elements of the list of tuple into float values.
Below is a demonstration for the same −
Example
my_list = [("45", "Jane"), ("11", "Will"), ("37.68", "86.78"), ("Rob", "89.90")] print("The list is : ") print(my_list) my_result = [] for tup in my_list: temp_val = [] for elem in tup: if elem.isalpha(): temp_val.append(elem) else: temp_val.append(float(elem)) my_result.append((temp_val[0],temp_val[1])) print("The float values are : " ) print(my_result)
Output
The list is : [('45', 'Jane'), ('11', 'Will'), ('37.68', '86.78'), ('Rob', '89.90')] The float values are : [(45.0, 'Jane'), (11.0, 'Will'), (37.68, 86.78), ('Rob', 89.9)]
Explanation
A list of tuples is defined and is displayed on the console.
An empty list is created.
The elements in the list of tuple is iterated over, and a temporary list is also created.
Every element is called using ‘isalpha’ method.
If it is an alphabet, the element is appended to the temporary list.
Otherwise, it is converted to float value and then appended to the temporary list.
These lists are displayed as output on the console.