To find the maximum value in a Python List without using the “max()” function:
my_list = [22, 15, 73, 215, 4, 7350, 113]
max_value = my_list[0]
for val in my_list:
if val > max_value:
max_value = val
print(max_value)
The result:
7350
Function to find the max value
Here is a function to find the maximum value in a List:
def find_max_value(my_list):
"""
Find the maximum value in a list
:param my_list: The List of values
:return: The max item in the list
"""
if not my_list:
raise ValueError("List is empty")
max_value = my_list[0]
for val in my_list:
if val > max_value:
max_value = val
return max_value
numbers_list = [22, 15, 73, 215, 4, 7350, 113]
print(find_max_value(numbers_list))
The result:
7350
Add a Pytest test
To test the “find_max_value” function using Pytest:
import pytest
# Assuming the find_max_value function is stored under app.number_operations
from app.number_operations import find_max_value
@pytest.mark.parametrize(
"input_list, expected_output",
[
([22, 15, 73, 215, 4, 7350, 113], 7350),
([3.14, 2.71, 1.618, 2.71828], 3.14),
(["apple", "banana", "orange", "kiwi"], "orange"),
([], None),
],
)
def test_find_max_value(input_list, expected_output):
"""
Test the find_max_value function across different input lists.
:param input_list: The input list
:param expected_output: The expected output of the max value, or an exception for an empty list
"""
if not input_list:
with pytest.raises(ValueError):
find_max_value(input_list)
else:
assert find_max_value(input_list) == expected_output
The result:
============================= test session starts =============================
collecting ... collected 4 items
test_number_operations.py::test_find_max_value[input_list0-7350] PASSED [ '25%']
test_number_operations.py::test_find_max_value[input_list1-3.14] PASSED [ '50%']
test_number_operations.py::test_find_max_value[input_list2-orange] PASSED [ '75%']
test_number_operations.py::test_find_max_value[input_list3-None] PASSED ['100%']
============================== 4 passed in '0.01s' ==============================
Additional Exercises
- Find the Min value in a Python List without using the min function
- Count the Number of Characters in a String in Python (without using the len function)
- How to Reverse a String in Python
- Count the Number of Spaces in a String in Python
- Count Vowels in a String in Python
- Count Consonants in a String in Python
- Count the number of times a character appears in a string in Python
- Find the Middle Item in a Python List