A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/maximum-of-two-numbers-in-python/ below:

Find Maximum of two numbers in Python

Find Maximum of two numbers in Python

Last Updated : 12 Jul, 2025

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))

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)

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)

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

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.

Related Articles

Find Maximum of two numbers in Python


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4