Python program to Convert a elements in a list of Tuples to Float
Last Updated :
26 Apr, 2023
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
test_list = [( "3" , "Gfg" ), ( "1" , "26.45" ), ( "7.32" , "8" ), ( "Gfg" , "8" )]
print ( "The original list is : " + str (test_list))
res = []
for tup in test_list:
temp = []
for ele in tup:
if ele.isalpha():
temp.append(ele)
else :
temp.append( float (ele))
res.append((temp[ 0 ],temp[ 1 ]))
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
test_list = [( "3" , "Gfg" ), ( "1" , "26.45" ), ( "7.32" , "8" ), ( "Gfg" , "8" )]
print ( "The original list is : " + str (test_list))
res = []
for tup in test_list:
temp = [ele if ele.isalpha() else float (ele) for ele in tup]
res.append((temp[ 0 ],temp[ 1 ]))
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
test_list = [( "3" , "Gfg" ), ( "1" , "26.45" ), ( "7.32" , "8" ), ( "Gfg" , "8" )]
print ( "The original list is : " + str (test_list))
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))
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
test_list = [( "3" , "Gfg" ), ( "1" , "26.45" ), ( "7.32" , "8" ), ( "Gfg" , "8" )]
print ( "The original list is : " + str (test_list))
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]
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
test_list = [( "3" , "Gfg" ), ( "1" , "26.45" ), ( "7.32" , "8" ), ( "Gfg" , "8" )]
print ( "The original list is : " + str (test_list))
res = []
for tup in test_list:
try :
temp = ( float (tup[ 0 ]), tup[ 1 ])
res.append(temp)
except ValueError:
res.append(tup)
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.
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
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
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
Convert List of Tuples to List of Strings - Python
The task is to convert a list of tuples where each tuple contains individual characters, into a list of strings by concatenating the characters in each tuple. This involves taking each tuple, joining its elements into a single string, and creating a new list containing these strings. For example, gi
3 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
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 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
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