
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Elements in a List of Tuples to Float in Python
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
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.
Advertisements