Lists and algorithms · beginner
Python Program to Find the Largest Element in a List
Find the largest number in a Python list with a loop, then with max(), and find the second largest correctly even when the largest value appears twice.
- for loop over a list
- max()
- sets
- sorted()
Finding the largest value by hand teaches the "best so far" pattern: keep the best value seen so far and replace it whenever a bigger one turns up. The same pattern finds the cheapest price, the longest word or the latest date.
The second largest number is a popular follow-up question, with a trap: in [8, 3, 8, 5] the answer is 5, not 8.
The program
numbers = [42, 7, 93, 18, 93, 64]
largest = numbers[0]
for n in numbers[1:]:
if n > largest:
largest = n
print("Largest:", largest)
second = None
for n in numbers:
if n < largest and (second is None or n > second):
second = n
print("Second largest:", second)Largest: 93
Second largest: 64How it works
- largest starts as the first element, so the program also works for lists of negative numbers.
- The loop compares each remaining element with the best so far and replaces it when the element is bigger.
- For the second largest, the program looks only at values smaller than the largest, so the duplicate 93 is skipped.
- second starts as None, meaning "nothing found yet". It stays None for a list such as [5, 5] that has no second distinct value.
Watch it run line by line
Watch largest in the global frame: it changes from 42 to 93 and then stays, even when the second 93 comes along. In the second loop, second goes 42 → 64.
“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: With max() and a set
max() finds the largest value. For the second largest, remove duplicates with set() and sort; this is simple but sorts the whole list, so the loop is faster for very long lists.
numbers = [42, 7, 93, 18, 93, 64]
print(max(numbers))
print(sorted(set(numbers))[-2])
print(max(numbers, key=abs), max(["kiwi", "banana", "fig"], key=len))93
64
93 bananaCommon mistakes
- Starting with largest = 0, which gives the wrong answer for a list of negative numbers such as [-5, -2, -9].
- Using sorted(numbers)[-2] for the second largest, which returns 93 when the largest value appears twice.
- Calling max() on an empty list raises ValueError. Use max(numbers, default=None) when the list may be empty.
Try it yourself
- Also print the position (index) of the largest element.
- Find the smallest and largest values in a single pass through the list.
Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 Python examples, or write your own program in the online Python Compiler.