Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Convert list of tuples to list of list
Next article icon

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

Last Updated : 26 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Tuple list, convert all possible convertible elements to float.

Input : test_list = [(“3”, “Gfg”), (“1”, “26.45”)] 
Output : [(3.0, ‘Gfg’), (1.0, 26.45)] 
Explanation : Numerical strings converted to floats.

Input : test_list = [(“3”, “Gfg”)] 
Output : [(3.0, ‘Gfg’)] 
Explanation : Numerical strings converted to floats. 

Method #1 : Using loop + isalpha() + float()

In this, we use a loop to iterate for all the tuples, check for alphabets using isalpha(), which cannot be converted to float, and for the rest of the elements float() is used to convert. 

Python3




# Python3 code to demonstrate working of
# Convert Tuple List elements to Float
# Using loop + isalpha() + float
 
# initializing list
test_list = [("3", "Gfg"), ("1", "26.45"), ("7.32", "8"), ("Gfg", "8")]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = []
for tup in test_list:
    temp = []
    for ele in tup:
         
        # check for string
        if ele.isalpha():
            temp.append(ele)
        else:
             
            # convert to float
            temp.append(float(ele))
    res.append((temp[0],temp[1]))
 
# printing result
print("The converted list : " + str(res))
 
 

Output:

The original list is : [(‘3’, ‘Gfg’), (‘1’, ‘26.45’), (‘7.32’, ‘8’), (‘Gfg’, ‘8’)] The converted list : [(3.0, ‘Gfg’), (1.0, 26.45), (7.32, 8.0), (‘Gfg’, 8.0)]

Time complexity: O(nm), where n is the length of the input list and m is the maximum number of elements in each tuple.
Auxiliary space: O(nm).

Method #2 : Using loop + isalpha() + float() + list comprehension

In this, we perform the task of iterating through inner tuples using list comprehension.

Python3




# Python3 code to demonstrate working of
# Convert Tuple List elements to Float
# Using loop + isalpha() + float
 
# initializing list
test_list = [("3", "Gfg"), ("1", "26.45"), ("7.32", "8"), ("Gfg", "8")]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = []
for tup in test_list:
       
    # list comprehension to check for each case
    temp = [ele if ele.isalpha() else float(ele) for ele in tup]
    res.append((temp[0],temp[1]))
 
# printing result
print("The converted list : " + str(res))
 
 

Output:

The original list is : [(‘3’, ‘Gfg’), (‘1’, ‘26.45’), (‘7.32’, ‘8’), (‘Gfg’, ‘8’)] The converted list : [(3.0, ‘Gfg’), (1.0, 26.45), (7.32, 8.0), (‘Gfg’, 8.0)]

Time Complexity: O(n*n)
Auxiliary Space: O(n)

Method 3: Using map() function and lambda expression

Use the map() function along with a lambda expression to achieve the same result. 

Python3




# Python3 code to demonstrate working of
# Convert Tuple List elements to Float
# Using map() + lambda
 
# initializing list
test_list = [("3", "Gfg"), ("1", "26.45"), ("7.32", "8"), ("Gfg", "8")]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using map() + lambda to convert tuple elements to float
res = list(map(lambda tup: (float(tup[0]) if not tup[0].isalpha() else tup[0],
                            float(tup[1]) if not tup[1].isalpha() else tup[1]), test_list))
 
# printing result
print("The converted list : " + str(res))
 
 
Output
The original list is : [('3', 'Gfg'), ('1', '26.45'), ('7.32', '8'), ('Gfg', '8')] The converted list : [(3.0, 'Gfg'), (1.0, 26.45), (7.32, 8.0), ('Gfg', 8.0)]

Time complexity: O(n), where n is the length of the input list. 
Auxiliary space: O(n), where n is the length of the input list. 

Method 4: Using list comprehension + try-except

You can use list comprehension and try-except to handle conversion of the tuple elements to float. This approach is similar to Method  but uses list comprehension instead of the map() function.

Python3




# initializing list
test_list = [("3", "Gfg"), ("1", "26.45"), ("7.32", "8"), ("Gfg", "8")]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using list comprehension + try-except to convert tuple elements to float
res = [(float(t[0]) if isinstance(t[0], str) and t[0].replace('.', '').isdigit() else t[0],
        float(t[1]) if isinstance(t[1], str) and t[1].replace('.', '').isdigit() else t[1])
       for t in test_list]
 
# printing result
print("The converted list : " + str(res))
 
 
Output
The original list is : [('3', 'Gfg'), ('1', '26.45'), ('7.32', '8'), ('Gfg', '8')] The converted list : [(3.0, 'Gfg'), (1.0, 26.45), (7.32, 8.0), ('Gfg', 8.0)]

The time complexity  is O(n), where n is the length of the input list, since it involves iterating over each element of the list and performing constant time operations.

The auxiliary space complexity  is also O(n), since it creates a new list with the same length as the input list to store the converted tuples.

Method 5 : Using try-except block

In this method, we will use a try-except block to convert the numeric elements of the tuple to float. If a non-numeric element is encountered, it will be kept as it is.

Algorithm:

Create an empty list to store the converted tuples.
Iterate over each tuple in the given list.
Use a try-except block to convert the first element of the tuple to float.
If the conversion is successful, then append the converted tuple to the result list.
If the conversion fails, then append the original tuple to the result list.
Return the result list.
Print the original and converted lists.

Python3




# Python3 code to demonstrate working of
# Convert Tuple List elements to Float
# Using try-except block
 
# initializing list
test_list = [("3", "Gfg"), ("1", "26.45"), ("7.32", "8"), ("Gfg", "8")]
 
# printing original list
print("The original list is : " + str(test_list))
 
# creating empty list for result
res = []
 
# iterating over each tuple in the given list
for tup in test_list:
    try:
        # converting the first element of the tuple to float
        temp = (float(tup[0]), tup[1])
        res.append(temp)
    except ValueError:
        # keeping the original tuple if conversion fails
        res.append(tup)
 
# printing result
print("The converted list : " + str(res))
 
 
Output
The original list is : [('3', 'Gfg'), ('1', '26.45'), ('7.32', '8'), ('Gfg', '8')] The converted list : [(3.0, 'Gfg'), (1.0, '26.45'), (7.32, '8'), ('Gfg', '8')] 

Time complexity: O(n), where n is the length of the given list of tuples.
Auxiliary space: O(n), where n is the length of the given list of tuples.



Next Article
Python | Convert list of tuples to list of list
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python tuple-programs
Practice Tags :
  • python

Similar Reads

  • Convert Set of Tuples to a List of Lists in Python
    Sets and lists are two basic data structures in programming that have distinct uses. It is sometimes necessary to transform a collection of tuples into a list of lists. Each tuple is converted into a list throughout this procedure, and these lists are subsequently compiled into a single, bigger list
    3 min read
  • Python | Convert list of tuples to list of list
    Converting list of tuples to list of lists in Python is a task where each tuple is transformed into list while preserving its elements. This operation is commonly used when we need to modify or work with the data in list format instead of tuples. Using numpyNumPy makes it easy to convert a list of t
    3 min read
  • Convert list of strings to list of tuples in Python
    Sometimes we deal with different types of data types and we require to inter-convert from one data type to another hence interconversion is always a useful tool to have knowledge. This article deals with the converse case. Let's discuss certain ways in which this can be done in Python. Method 1: Con
    5 min read
  • Python - Convert List of Lists to Tuple of Tuples
    Sometimes, while working with Python data, we can have a problem in which we need to perform interconversion of data types. This kind of problem can occur in domains in which we need to get data in particular formats such as Machine Learning. Let us discuss certain ways in which this task can be per
    8 min read
  • Python program to convert a byte string to a list of integers
    We have to convert a byte string to a list of integers extracts the byte values (ASCII codes) from the byte string and stores them as integers in a list. For Example, we are having a byte string s=b"Hello" we need to write a program to convert this string to list of integers so the output should be
    2 min read
  • Python program to convert exponential to float
    Given a number in exponential format, the task is to write a Python program to convert the number from exponential format to float. The exponential number is a way of representing a number. Examples: Input: 1.900000e+01 Output: 19.0 Input: 2.002000e+03 Output: 2002.0 Input: 1.101020e+05 Output: 1101
    1 min read
  • Python Program to Convert Tuple Matrix to Tuple List
    Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]
    8 min read
  • Python program to convert float to exponential
    Given a float number, the task is to write a Python program to convert float to exponential. Examples: Input: 19.0 Output: 1.900000e+01 Input: 200.2 Output: 2.002000e+02 Input: 1101.02 Output: 1.101020e+03Approach: We will first declare and initialise a float number.Then we will use format method to
    1 min read
  • Convert List Of Tuples To Json String in Python
    We have a list of tuples and our task is to convert the list of tuples into a JSON string in Python. In this article, we will see how we can convert a list of tuples to a JSON string in Python. Convert List Of Tuples To Json String in PythonBelow, are the methods of Convert List Of Tuples To Json St
    3 min read
  • Python - Convert a list into tuple of lists
    When working with data structures in Python, there are times when we need to convert a list into a tuple of smaller lists. For example, given a list [1, 2, 3, 4, 5, 6], we may want to split it into a tuple of two lists like ([1, 2, 3], [4, 5, 6]). We will explore different methods to achieve this co
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences