The Wayback Machine - https://web.archive.org/web/20240914102528/https://www.geeksforgeeks.org/python-min-max-value-in-float-string-list/
Open In App

Python | Min/Max value in float string list

Last Updated : 08 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Sometimes, while working with a Python list, we can have a problem in which we need to find min/max value in the list. But sometimes, we don’t have a natural number but a floating-point number in string format. This problem can occur while working with data, both in web development and Data Science domain. Let’s discuss a way in which this problem can be solved. 

Method 1: Using min()/max() + float() 
This problem can be solved using the min or max function in which we first convert the strings into float and then pass this logic in functions in respective min/max function. 

Python3




# Python3 code to demonstrate working of
# Min / Max value in float string list
# using min()/max() + float() + generator
 
# initialize lists
test_list = ['4.5', '7.8', '9.8', '10.3']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Min / Max value in float string list
# using min()/max() +float + lambda function
res_min = min(test_list,key=lambda x:float(x))
res_max = max(test_list,key=lambda x:float(x))
 
# printing result
print("The min value of list : " + str(res_min))
print("The max value of list : " + str(res_max))


Output

The original list is : ['4.5', '7.8', '9.8', '10.3']
The min value of list : 4.5
The max value of list : 10.3

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

Method 2: Using the built-in reduce() function along with the lambda function to find the minimum and maximum values.

Using the built-in reduce() function along with the lambda function is one approach to finding the minimum and maximum values in a list of float strings. The reduce() function applies a given function to the elements of an iterable, cumulatively reducing them to a single value. By passing in a lambda function that compares the current minimum or maximum value to the next element in the list, the reduce() function can be used to find the minimum or maximum value.

Python3




from functools import reduce
 
test_list = ['4.5', '7.8', '9.8', '10.3']
 
# Find minimum value
res_min = reduce(lambda x, y: x if float(x) < float(y) else y, test_list)
 
# Find maximum value
res_max = reduce(lambda x, y: x if float(x) > float(y) else y, test_list)
 
# printing result
print("The min value of list : " + str(res_min))
print("The max value of list : " + str(res_max))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The min value of list : 4.5
The max value of list : 10.3

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

Method #3:  Use a for loop and convert each element to float before comparing them.

Step-by-step approach:

  • Initialize variables for minimum and maximum values to None.
  • Iterate through the list using a for loop.
  • Convert each element to float using the float() function.
  • Compare the float value to the current minimum value. If the value is less than the current minimum value or if the minimum value is None, update the minimum value.
  • Compare the float value to the current maximum value. If the value is greater than the current maximum value or if the maximum value is None, update the maximum value.
  • After iterating through the entire list, the minimum and maximum values will be stored in their respective variables.
  • Print the minimum and maximum values.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Min / Max value in float string list
# using for loop and float()
 
# initialize list
test_list = ['4.5', '7.8', '9.8', '10.3']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize variables for minimum and maximum values
min_val = None
max_val = None
 
# iterate through the list and find minimum and maximum values
for elem in test_list:
    float_elem = float(elem)
    if min_val is None or float_elem < min_val:
        min_val = float_elem
    if max_val is None or float_elem > max_val:
        max_val = float_elem
 
# printing result
print("The min value of list : " + str(min_val))
print("The max value of list : " + str(max_val))


Output

The original list is : ['4.5', '7.8', '9.8', '10.3']
The min value of list : 4.5
The max value of list : 10.3

Time complexity: O(n), where n is the length of the list.
Auxiliary space: O(1), as we only need to store two variables for the minimum and maximum values.

Method 5: Using numpy library

step-by-step approach :

  1. Import the numpy library using the statement import numpy as np.
  2. Define the input list test_list with string elements as [‘4.5’, ‘7.8’, ‘9.8’, ‘10.3’].
  3. Convert the input list to a numpy array of float elements using the np.array() method and assign it to a variable float_arr. The dtype parameter is set to float to ensure that the elements are of float data type.
  4. Use the np.min() function to get the minimum value from the float_arr array and assign it to a variable min_val.
  5. Use the np.max() function to get the maximum value from the float_arr array and assign it to a variable max_val.
  6. Print the result using the print() function. The minimum value and maximum value are printed using the variables min_val and max_val respectively.

Python3




# Python3 code to demonstrate working of
# Min / Max value in float string list
# using numpy
 
import numpy as np
 
# initialize list
test_list = ['4.5', '7.8', '9.8', '10.3']
 
# convert the list of string elements to a numpy array of float elements
float_arr = np.array(test_list, dtype=float)
 
# get the minimum and maximum values from the array
min_val = np.min(float_arr)
max_val = np.max(float_arr)
 
# printing result
print("The min value of list : " + str(min_val))
print("The max value of list : " + str(max_val))


OUTPUT:
The min value of list : 4.5
The max value of list : 10.3

The time complexity of this method is O(n) to convert the string list to a numpy array, and O(1) to get the minimum and maximum values using numpy functions. So the overall time complexity is O(n).

Auxiliary space: This method requires extra space to store the numpy array, which has a space complexity of O(n).



Similar Reads

Check If Value Is Int or Float in Python
In Python, you might want to see if a number is a whole number (integer) or a decimal (float). Python has built-in functions to make this easy. There are simple ones like type() and more advanced ones like isinstance(). In this article, we'll explore different ways to check if a value is an integer or float in Python. To Check If Value Is Int Or Fl
4 min read
How to Fix "TypeError: list indices must be integers or slices, not float" in Python
Python is a versatile and powerful programming language used in various fields from web development to data analysis. However, like any programming language, Python can produce errors that might seem confusing at first. One such common error is the TypeError: list indices must be integers or slices not float. Understanding this error and knowing ho
4 min read
Python | Check for float string
One of the most notable breakthrough that Python brought was that the interconversion between the datatypes was done in a very easy manner and hence making it quite powerful. String can be converted to integers easily, but converting a float value is still difficult task. Let's discuss certain ways in which one can check if string is a float to avo
4 min read
Convert Python String to Float datatype
Let us see how to convert a string object into a float object. We can do this by using these functions : float() decimal() Method 1: Using float() # declaring a string str1 = &quot;9.02&quot; print(&quot;The initial string : &quot; + str1) print(type(str1)) # converting into float str2 = float(str1) print(&quot;\nThe conversion of string to float i
2 min read
Convert String to Float in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing information about converting the string to float. In Python, we can use float() to convert String to float. and we can use int() to convert a String to an integer. Input: "33.28" Output: 33.28 # float Explanation: int in input a
3 min read
Convert String with Comma To Float in Python
When working with data in Python, it's not uncommon to encounter numeric values formatted with a mix of commas and dots as separators. Converting such strings to float is a common task, and Python offers several simple methods to achieve this. In this article, we will explore five generally used methods for converting a string with a comma separato
3 min read
Cannot Convert String To Float in Python
Python, a versatile and powerful programming language, is widely used for data manipulation and analysis. However, developers often encounter challenges, one of which is the "Cannot Convert String To Float" error. This error occurs when attempting to convert a string to a float, but the string's content is incompatible with the float data type. In
3 min read
Convert hex string to float in Python
Converting a hex string to a float in Python involves a few steps since Python does not have a direct method to convert a hexadecimal string representing a float directly to a float. Typically, a hexadecimal string is first converted to its binary representation, and then this binary representation is interpreted as a floating-point number. Convert
3 min read
How to Convert String to Float in Pandas DataFrame
Converting Strings to Float in Pandas DataFrame is a very crucial step for data analysis. Converting string to float values can help you perform various arithmetic operations and plot graphs. In this article, we'll look at different ways to convert a string to a float in DataFrame. Creating Sample Dataframe Now, let's create a DataFrame with 'Year'
4 min read
float() in Python
Python float() function is used to return a floating-point number from a number or a string representation of a numeric value. Example: Here is a simple example of the Python float() function which takes an integer as the parameter and returns its float value. C/C++ Code # convert integer value to float num = float(10) print(num) Output: 10.0Python
3 min read
Python | Sort a tuple by its float element
In this article, we will see how we can sort a tuple (consisting of float elements) using its float elements. Here we will see how to do this by using the built-in method sorted() and how can this be done using in place method of sorting. Examples: Input : tuple = [('lucky', '18.265'), ('nikhil', '14.107'), ('akash', '24.541'), ('anand', '4.256'),
3 min read
Python | Float type and its methods
The float type in Python represents the floating point number. Float is used to represent real numbers and is written with a decimal point dividing the integer and fractional parts. For example, 97.98, 32.3+e18, -32.54e100 all are floating point numbers. Python float values are represented as 64-bit double-precision values. The maximum value any fl
3 min read
Python | Float Layout in Kivy
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. &#128073;&#127997; Kivy Tutorial - Learn Kivy with Examples. FloatLayout: Floatlayout allows us to place the eleme
5 min read
Python | Filter out integers from float numpy array
Given a numpy array, the task is to filter out integers from an array containing float and integers. Let's see few methods to solve a given task. Method #1 : Using astype(int) C/C++ Code # Python code to demonstrate # filtering integers from numpy array # containing integers and float import numpy as np # initialising array ini_array = np.array([1.
2 min read
Python | sympy.Float() method
With the help of sympy.Float() method, we can convert the integer values to floating point values and by using this method we can also set the values of precision. By default value of precision is 15. Syntax : sympy.Float() Return : Return the floating point number. Example #1 : In this example we can see that by using sympy.Float() method, we can
1 min read
Display scientific notation as float in Python
In this article, the task is to display the scientific notation as float in Python. The scientific notation means any number expressed in the power of 10.for example- 340 can be written in scientific notation as 3.4 X102.in pythons, we use str.format() on a number with "{:e}" to format the number to scientific notation. str.format() formats the num
2 min read
Generate a Vandermonde Matrix of the Legendre Polynomial with Float Array of Points in Python using NumPy
In this article, we will be looking at the approach to generating a Vandermonde matrix of the Legendre polynomial with a float array of points in Python using NumPy. Example: Array: [-1.57 0.58 -3.57 1.44 2.75] Result: [[ 1.000000e+00 -1.570000e+00 3.197350e+00] [ 1.000000e+00 5.800000e-01 4.600000e-03] [ 1.000000e+00 -3.570000e+00 1.861735e+01] [
3 min read
ZeroDivisionError: float division by zero in Python
In this article, we will see what is ZeroDivisionError and also different ways to fix this error. What is ZeroDivisionError?A ZeroDivisionError in Python occurs when we try to divide a number by 0. We can't divide a number by 0 otherwise it will raise an error. Let us understand it with the help of an example. In this example, we are dividing a num
2 min read
How To Fix "Typeerror: Can'T Convert 'Float' Object To Str Implicitly" In Python
In this article, we'll delve into understanding of typeerror and how to fix "Typeerror: Can'T Convert 'Float' Object To Str Implicitly" In Python. Types of Errors in Python Script ExecutionThere are many different types of errors that can occur while executing a python script. These errors indicate different meanings and are typically classified in
3 min read
Overflowerror: Convert Int Large to Float in Python
Python overflows when an arithmetic operation yields a number that cannot be represented as a floating point. This happens particularly in the case of very large numbers or complex calculations that go beyond the scope of the Python interpreter. The OverflowError is raised to indicate that the result could not be contained within those constraints.
4 min read
How to fix AttributeError: module numpy has no attribute float' in Python
While working with the Python NumPy module, you might encounter the error "module 'numpy' has no attribute 'float'". This error arises because numpy's float attribute has been deprecated and removed in favor of using standard Python types. In this article, we will learn how to fix "AttributeError: module 'numpy' has no attribute 'float'". What is A
2 min read
How to Fix "TypeError: 'float' object is not callable" in Python
In Python, encountering the error message "TypeError: 'float' object is not callable" is a common issue that can arise due to the misuse of the variable names or syntax errors. This article will explain why this error occurs and provide detailed steps to fix it along with the example code and common troubleshooting tips. Understanding the ErrorThe
4 min read
How to convert Float to Int in Python?
Converting a float value to an int is done by Type conversion, which is an explicit method of converting an operand to a specific type. However, it is to be noted that such type of conversion may tend to be a lossy one (loss of data). Converting an int value like 2 to floating-point will result in 2.0, such types of conversion are safe as there wou
6 min read
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
PyQt5 QSpinBox - Getting float point size | pointSizeF() method
In this article we will see how we can get the floating point size of the text in spin box. Changing the point size will change the size of the text, pixel and point are two different things some point can have multiple pixels inside it. It is recommended to change point size for changing the size of the text. Unlike normal point size, floating poi
2 min read
PyQt5 QSpinBox - Setting float point size | setPointSizeF() method
In this article we will see how we can set the floating-point size of the text in spin box. Changing the point size will change the size of the text, pixel and point are two different things some point can have multiple pixels inside it. It is recommended to change point size for changing the size of the text. Unlike normal point size floating-poin
2 min read
PyQt5 QCalendarWidget - Device Pixel Ratio Float
In this article we will see how we can get device pixel ratio, float value of the QCalendarWidget. The device pixel ratio is the ratio between physical pixels and logical pixels of the calendar. Common values are 1 for normal-dpi displays and 2 for high-dpi “retina” displays, for some devices it is in decimal values like 1.1, 1.2 etc . In order to
2 min read
How to Convert Float to Datetime in Pandas DataFrame?
Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to Datetime, String to Integer, Float to Datetime, etc. For converting float to DateTime we use pandas.to_datetime() function and following syntax is used : Syntax: pandas.to_datetime(arg, errors=’raise’, dayfirst=
3 min read
How to Fix: TypeError: ‘numpy.float’ object is not callable?
In this article, we are going to see how to fix TypeError: ‘numpy.float’ object is not callable in Python. There is only one case in which we can see this error: If we try to call a NumPy array as a function, we are most likely to get such an error. Example: C/C++ Code import numpy as np a = np.array([1,2,3]) a() Output: TypeError: 'numpy.ndarray'
1 min read
How to Fix: ValueError: cannot convert float NaN to integer
In this article we will discuss how to fix the value error - cannot convert float NaN to integer in Python. In Python, NaN stands for Not a Number. This error will occur when we are converting the dataframe column of the float type that contains NaN values to an integer. Let's see the error and explore the methods to deal with it. Dataset in use: L
3 min read
Article Tags :
Practice Tags :