Write Python code to find the largest number in a list.
💡 Model Answer
You can find the largest number in a list by iterating through the list and keeping track of the maximum value seen so far. Here is a simple implementation:
def find_max(numbers):
if not numbers:
raise ValueError("List is empty")
max_val = numbers[0]
for num in numbers[1:]:
if num > max_val:
max_val = num
return max_val
# Example usage
my_list = [3, 7, 2, 9, 4]
print(find_max(my_list)) # Output: 9
Python also provides a built‑in max() function that does the same in one line: max(numbers). The time complexity of the manual approach is O(n) because it examines each element once, and the space complexity is O(1) as only a few variables are used. This solution works for any comparable data type, not just integers.
Sign in to unlock the rest of this answer
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500