When it is required to convert a tuple to a float value, the 'join' method, 'float' method, 'str' method and generator expression can be used.
Generator is a simple way of creating iterators. It automatically implements a class with '__iter__()' and '__next__()' methods and keeps track of the internal states, as well as raises 'StopIteration' exception when no values are present that could be returned.
The 'float' method converts a given element to float data type.
The 'str' method converts the given element into string data type.
Below is a demonstration of the same −
Example
my_tuple_1 = ( 7, 8) print ("The first tuple is : " ) print(my_tuple_1) my_result = float('.'.join(str(elem) for elem in my_tuple_1)) print("After converting the tuple to float, the tuple is : ") print(my_result)
Output
The first tuple is : (7, 8) After converting the tuple to float, the tuple is : 7.8
Explanation
- A tuple is defined and is displayed on the console.
- The '.' operator and 'join' method is used to join the two elements in the tuple as a decimal number.
- This result is assigned to a variable.
- It is displayed as output on the console.