Skip to main content

How to find the range of elements in a list in Python

How to find the range of elements in a list in Python.

Here is a step-by-step tutorial on how to find the range of elements in a list in Python:

Step 1: Create a list

To begin, you need to create a list that contains the elements for which you want to find the range. You can do this by assigning a list of values to a variable. For example:

my_list = [5, 2, 9, 4, 7]

Step 2: Find the minimum and maximum values

Next, you need to find the minimum and maximum values in the list. Python provides built-in functions called min() and max() that can be used to find these values. You can use them as follows:

minimum = min(my_list)
maximum = max(my_list)

Step 3: Calculate the range

Once you have the minimum and maximum values, you can calculate the range by subtracting the minimum from the maximum. In Python, this can be done using the minus operator -. Here's an example:

range_of_elements = maximum - minimum

Step 4: Print or use the range

Finally, you can print the range of elements or use it for further calculations or comparisons. For example:

print("The range of elements in the list is:", range_of_elements)

Alternatively, you can directly use the range value in your code:

if range_of_elements > 10:
print("The range is greater than 10.")
else:
print("The range is not greater than 10.")

Here's the complete code altogether:

my_list = [5, 2, 9, 4, 7]
minimum = min(my_list)
maximum = max(my_list)
range_of_elements = maximum - minimum
print("The range of elements in the list is:", range_of_elements)

That's it! You have successfully found the range of elements in a list using Python.