To find the range (i.e., the difference between the largest and smallest number) of a list of numbers in Python, we can make use of the built-in min()
and max()
functions, like so:
main.py98 chars4 lines
In the code above, we first define a list of numbers my_list
containing [1, 5, -2, 10, 12]
. We then use the min()
function to find the smallest number in the list, which is -2
, and the max()
function to find the largest number in the list, which is 12
. Finally, we subtract the smallest number from the largest number to find the range of the list, which is 14
.
Note that this method assumes that the list is not empty and that all elements of the list are numeric. If the list is empty, or if it contains non-numeric elements, this code may raise an error.
gistlibby LogSnag