Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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].

BeginnerPhase 4 - Level 1: Basic ArraysExample 3 of 10
maximum-element.py
1# Array
2arr = [10, 25, 5, 30, 15]
3
4# Find maximum
5max_element = arr[0]
6for element in arr:
7 if element > max_element:
8 max_element = element
9
10print(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. 1

    Set max_element to arr[0].

  2. 2

    Compare every element with the candidate.

  3. 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.