Python program to convert elements in a list of Tuples to Float

PythonServer Side ProgrammingProgramming

When it is required to convert elements in a list of tuples to float values, the ‘isalpha’ method, the ‘float’ method, and a simple iteration is used.

Below is a demonstration of the same −

Example

 Live Demo

my_list = [("31", "py"), ("22", "226.65"), ("18.12", "17"), ("pyt", "12")]

print("The list is :")
print(my_list)

my_result = []
for index in my_list:
   my_temp = []
   for element in index:

      if element.isalpha():
         my_temp.append(element)
      else:

         my_temp.append(float(element))
   my_result.append((my_temp[0],my_temp[1]))

print("The result is :")
print(my_result)

Output

The list is :
[('31', 'py'), ('22', '226.65'), ('18.12', '17'), ('pyt', '12')]
The result is :
[(31.0, 'py'), (22.0, 226.65), (18.12, 17.0), ('pyt', 12.0)]

Explanation

  • A list of list with integers is defined and is displayed on the console.

  • An empty list is declared.

  • The list is iterated over, and the element is checked for alphabet using isalpha() function.

  • If the condition is satisfied, the element is appended as it is and if the condition fails, the element is converted to float and appended.

  • This result is assigned to a variable.

  • This is the output that is displayed on the console.

raja
Published on 04-Sep-2021 11:22:04
Advertisements