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
# 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))
OutputThe 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))
OutputThe 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))
OutputThe 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 tu
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 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 - 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 con
3 min read
Python | Convert list of tuples into list In Python we often need to convert a list of tuples into a flat list, especially when we work with datasets or nested structures. In this article, we will explore various methods to Convert a list of tuples into a list. Using itertools.chain() itertools.chain() is the most efficient way to flatten a
3 min read
Convert Dictionary to List of Tuples - Python Converting a dictionary into a list of tuples involves transforming each key-value pair into a tuple, where the key is the first element and the corresponding value is the second. For example, given a dictionary d = {'a': 1, 'b': 2, 'c': 3}, the expected output after conversion is [('a', 1), ('b', 2
3 min read