How can I get the index of the max or min value in a list using Python?
I’m working on a minimax algorithm and using Python’s max()
and min()
functions on a list to evaluate moves. I need to find the index of the value returned by max()
(for the first player’s turn) or min()
(for the second player’s turn). Specifically, I want to know which move corresponds to the max or min value.
Here’s a snippet of my code:
for i in range(9):
new_board = current_board.new_board_with_move([i // 3, i % 3], player)
if new_board:
temp = min_max(new_board, depth + 1, not is_min_level)
values.append(temp)
if is_min_level:
return min(values)
else:
return max(values)
I need to modify the code to return the index of the max or min value instead of just the value itself. Could you explain how to get index of max value in list python
?
Hello Everyone!
Using max()
or min()
with index()
One way to find the index of the maximum or minimum value is by first getting the value using max()
or min()
and then calling the index()
method to find its position. Here’s an example:
for i in range(9):
new_board = current_board.new_board_with_move([i // 3, i % 3], player)
if new_board:
temp = min_max(new_board, depth + 1, not is_min_level)
values.append(temp)
if is_min_level:
min_value = min(values)
return values.index(min_value) # Index of min value
else:
max_value = max(values)
return values.index(max_value) # Index of max value
That works, @yanisleidi-rodriguez! But you can make it more elegant by using enumerate()
. With enumerate()
, you can get both the index and value while iterating, and you avoid the extra call to index()
. Here’s an enhanced version:
for i in range(9):
new_board = current_board.new_board_with_move([i // 3, i % 3], player)
if new_board:
temp = min_max(new_board, depth + 1, not is_min_level)
values.append(temp)
if is_min_level:
min_value = min(values)
min_index = next(index for index, value in enumerate(values) if value == min_value)
return min_index # Index of min value
else:
max_value = max(values)
max_index = next(index for index, value in enumerate(values) if value == max_value)
return max_index # Index of max value
Nice points, @panchal_archanaa! But we can simplify this even further using the key
argument in max()
or min()
. This avoids the need for enumerate()
or an additional iteration to compare values. Here’s the optimized version:
for i in range(9):
new_board = current_board.new_board_with_move([i // 3, i % 3], player)
if new_board:
temp = min_max(new_board, depth + 1, not is_min_level)
values.append(temp)
if is_min_level:
return min(range(len(values)), key=values.__getitem__) # Index of min value
else:
return max(range(len(values)), key=values.__getitem__) # Index of max value