Index of Maximum Element
Find the zero-based position of a list's maximum. Students track both a candidate value and its index and see why equal maxima keep the first position.
1# Take array2n = int(input("Enter array size: "))3arr = []4for i in range(n):5 arr.append(int(input(f"Element {i+1}: ")))67# Find index of max8max_index = 09max_value = arr[0]1011for i in range(1, len(arr)):12 if arr[i] > max_value:13 max_value = arr[i]14 max_index = i1516print(f"Index of maximum: {max_index}")
Output
Enter array size: 5 Element 1: 10 Element 2: 25 Element 3: 5 Element 4: 30 Element 5: 15 Index of maximum: 3
In this one
- Track a value-index pair
- Use zero-based positions
- Retain first tied maxima
How it works
- 1
Initialize max_index zero and max_value from arr[0].
- 2
Scan later indexes for a larger value.
- 3
Update both candidate fields together before printing the index.
Edge cases
What if the maximum repeats?
What if the maximum repeats?
The first occurrence's index is kept.
What if n = 0?
What if n = 0?
arr[0] raises IndexError.
What's going on
The initial maximum and index come from position zero. The loop then scans positions one through the last valid index.
A strictly larger value updates max_value and max_index together. Equal values do not replace them, so ties keep the first maximum's index. The input must be nonempty because arr[0] is read before the scan begins.
What if the maximum repeats? The first occurrence's index is kept.
What if n = 0? arr[0] raises IndexError.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Does the output use one-based positions?
Pick an answer to check it.
Question 2
What if the maximum repeats?
Pick an answer to check it.
Questions people ask
What if the maximum repeats?
The first occurrence's index is kept.
What if n = 0?
arr[0] raises IndexError.
Does the output use one-based positions?
No, it reports a zero-based index.
๐Related Content
- ๐
Phase 4 - Learn Concepts
Review Phase 4 concepts and explanations
- ๐
Phase 4 - Quiz
Test your Phase 4 understanding with quiz questions
- ๐ป
Phase 4 - All Practice Problems
Explore all practice problems for Phase 4
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum