Maximum Element
Find a list's maximum with a manual Python scan. Students initialize from actual data, update a candidate, and understand why empty input cannot supply arr[0].
1# Array2arr = [10, 25, 5, 30, 15]34# Find maximum5max_element = arr[0]6for element in arr:7 if element > max_element:8 max_element = element910print(f"Maximum element: {max_element}")
Output
Maximum element: 30
In this one
- Initialize from real data
- Replace a maximum candidate
- Handle all-negative values
How it works
- 1
Set max_element to arr[0].
- 2
Compare every element with the candidate.
- 3
Replace it only for a larger value, then print.
Edge cases
Why not initialize to zero?
Why not initialize to zero?
An all-negative list could then report a value absent from the data.
What if the list is empty?
What if the list is empty?
arr[0] raises IndexError.
What's going on
max_element begins at the first stored value, not zero. This keeps the algorithm valid even when every element is negative.
Each larger value replaces the candidate. In the sample, twenty-five replaces ten and thirty later replaces twenty-five. Smaller values leave it unchanged. The loop also rechecks the first element harmlessly; a genuinely empty list would fail at initialization.
Why not initialize to zero? An all-negative list could then report a value absent from the data.
What if the list is empty? arr[0] raises IndexError.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which comparison updates the maximum?
Pick an answer to check it.
Question 2
Why not initialize to zero?
Pick an answer to check it.
Questions people ask
Why not initialize to zero?
An all-negative list could then report a value absent from the data.
What if the list is empty?
arr[0] raises IndexError.
Which comparison updates the maximum?
element > max_element.
๐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