Find the Min value in a Python List without using the min function

To find the minimum value in a Python List, without using the “min()” function:

my_list = [54, 890, 25, 12500, 7, 115]

min_value = my_list[0]

for val in my_list:
if val < min_value:
min_value = val

print(min_value)

The result:

7

Function to find the min value

Here is a function to find the minimum value in a List:

def find_min_value(my_list):
"""
Find the minimum value in a list

:param my_list: The input list
:return: The minimum value in the list
"
""
if not my_list:
raise ValueError("List is empty")

min_value = my_list[0]

for val in my_list:
if val < min_value:
min_value = val
return min_value


list_of_numbers = [54, 890, 25, 12500, 7, 115]

print(find_min_value(list_of_numbers))

The result:

7

Add a Pytest test

To test the “find_min_value” function using Pytest:

import pytest

# Assuming the find_min_value function is stored under app.number_operations
from app.number_operations import find_min_value


@pytest.mark.parametrize(
"input_list, expected_output",
[
([54, 890, 25, 12500, 7, 115], 7),
([3.14, 2.71, 1.618, 2.71828], 1.618),
(["apple", "banana", "orange", "kiwi"], "apple"),
([], None),
],
)
def test_find_min_value(input_list, expected_output):
"""
Test the find_min_value function across different lists

:param input_list: The input list
:param expected_output: The expected output of the min value, or an exception for an empty list
"
""
if not input_list:
with pytest.raises(ValueError):
find_min_value(input_list)
else:
assert find_min_value(input_list) == expected_output

The result:

============================= test session starts =============================
collecting ... collected 4 items

test_number_operations.py::test_find_min_value[input_list0-7] PASSED [' 25%']
test_number_operations.py::test_find_min_value[input_list1-1.618] PASSED [ '50%']
test_number_operations.py::test_find_min_value[input_list2-apple] PASSED [ '75%']
test_number_operations.py::test_find_min_value[input_list3-None] PASSED ['100%']

============================== 4 passed in '0.02s' ==============================

Additional Exercises

Leave a Comment