Open In App

Find Maximum of two numbers in Python

Last Updated : 09 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Finding the maximum of two numbers in Python helps determine the larger of the two values. For example, given two numbers a = 7 and b = 3, you may want to extract the larger number, which in this case is 7. Let's explore different ways to do this efficiently.

Using max()

max() function is the most optimized solution for finding the maximum among two or more values. It is widely used due to its simplicity, performance and readability. Internally implemented in C, it offers the best efficiency in real-world scenarios.

Python
a = 7
b = 3
print(max(a, b))

Output
7

Explanation: max(a, b) compares the two values and returns 7, the greater number.

Using ternary operator

Ternary conditional operator provides a compact, single-line way to choose between two values based on a condition. This method is ideal when you want a concise syntax without sacrificing readability, especially useful in return statements or inline assignments.

Python
a = 7
b = 3
print(a if a > b else b)

Output
7

Explanation: if a > b else b checks if a is greater than b. If true, it returns a; otherwise, it returns b. In this case, since 7 > 3, it returns 7, which is then printed.

Using if-Else statement

It is highly readable and a great choice for beginners learning control structures. Though slightly more verbose, it clearly expresses the logic step-by-step.

Python
a = 7
b = 3

if a > b:
    print(a)
else:
    print(b)

Output
7

Explanation: The if statement checks whether a is greater than b. If true, it prints a; otherwise, it prints b. Since 7 > 3, the condition is true, so 7 is printed.

Using sort()

In this approach, the two numbers are stored in a list, which is then sorted to find the maximum. Although this method works correctly, it introduces unnecessary computational overhead, making it inefficient for such a simple task.

Python
a = 7
b = 3

num = [a, b]
num.sort()
print(num[-1])

Output
7

Explanation: sort() arranges the list in ascending order, placing the largest number at the last position. Using num[-1] accesses the maximum value. Since 7 is greater than 3, the list becomes [3, 7] and num[-1] returns 7.


Next Article
Article Tags :
Practice Tags :

Similar Reads