The Wayback Machine - https://web.archive.org/web/20240926195556/https://www.geeksforgeeks.org/maximum-of-two-numbers-in-python/
Open In App

Find Maximum of two numbers in Python

Last Updated : 25 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two numbers, write a Python code to find the Maximum of these two numbers.

Examples: 

Input: a = 2, b = 4
Output: 4

Input: a = -1, b = -4
Output: -1


Find Maximum of two numbers in Python

This is the naive approach where we will compare two numbers using if-else statement and will print the output accordingly.

Example: 

Python
# Python program to find the
# maximum of two numbers


def maximum(a, b):
    
    if a >= b:
        return a
    else:
        return b
    
# Driver code
a = 2
b = 4
print(maximum(a, b))

Output
4

Time complexity: O(1)
Auxiliary space: O(1)

Find Maximum of two numbers Using max() function

This function is used to find the maximum of the values passed as its arguments.

Example: 

Python
# Python program to find the
# maximum of two numbers


a = 2
b = 4

maximum = max(a, b)
print(maximum)

Output
4

Time complexity: O(1)
Auxiliary space: O(1)


Maximum of two numbers Using Ternary Operator

This operator is also known as conditional expression are operators that evaluate something based on a condition being true or false. It simply allows testing a condition in a single line

Example:

Python
# Python program to find the
# maximum of two numbers
    
# Driver code
a = 2
b = 4

# Use of ternary operator
print(a if a >= b else b)

Output
4

Time complexity: O(1)
Auxiliary space: O(1)

Maximum of two numbers Using lambda function 

Python
# python code to find maximum of two numbers

a=2;b=4
maximum = lambda a,b:a if a > b else b
print(f'{maximum(a,b)} is a maximum number')

Output:

4 is a maximum number

Maximum of two numbers Using list comprehension

Python
a=2;b=4
x=[a if a>b else b] 
print("maximum number is:",x)

Output
maximum number is: [4]

Maximum of two numbers Using sort() method

Python
# Python program to find the
# maximum of two numbers
a = 2
b = 4
x=[a,b]
x.sort()
print(x[-1])

Output
4

Time Complexity : O(NlogN)
Auxiliary Space : O(1)

Find Maximum of two numbers in Python – FAQs

How to Find the Maximum of Two Numbers in Python?

You can find the maximum of two numbers in Python using the built-in max() function, conditional statements, or lambda functions.

What is the max() Function in Python?

The max() function returns the largest of the input values.

Syntax:

max(a, b)

Example:

a = 5
b = 10
maximum = max(a, b)
print(maximum) # Output: 10

How to Use Conditional Statements to Find Maximum?

You can use if-else conditional statements to find the maximum of two numbers.

Example:

a = 5
b = 10

if a > b:
maximum = a
else:
maximum = b

print(maximum) # Output: 10

What are Python Lambda Functions?

Lambda functions in Python are small anonymous functions defined using the lambda keyword. They can have any number of arguments but only one expression. The expression is evaluated and returned.

Syntax:

lambda arguments: expression

Example:

# Lambda function to find maximum of two numbers
max_func = lambda a, b: a if a > b else b

a = 5
b = 10
maximum = max_func(a, b)
print(maximum) # Output: 10

How to Compare Two Numbers Using Ternary Operators?

Ternary operators provide a way to condense an if-else statement into a single line. In Python, it is done using the syntax:

Syntax:

a if condition else b

Example:

a = 5
b = 10

maximum = a if a > b else b
print(maximum) # Output: 10


Previous Article
Next Article

Similar Reads

Find the sum and maximum value of the two column in excel file using Pandas
In these articles, we will discuss how to read data from excel and perform some mathematical operation and store it into a new column in DataFrame. Suppose our excel file looks like this. Then we have to compute the sum of two-column and find out the maximum value and store into a new DataFrame column. Approach : Import Pandas module.Read data from
2 min read
Return the maximum of an array along axis 0 or maximum ignoring any NaNs in Python
In this article, we will see how to return the maximum of an array along axis 0 or maximum ignoring any NaNs in Python. ExampleInput: [[ 1. 0. 3.] [10. nan 30.] [nan 10. 20.]] Output: [10. 10. 30.] Explanation: An array with maximum values.nanmax method in PythonPython provides a nanmax method that returns the maximum of an array along a specified
3 min read
Return the maximum of an array or maximum ignoring any NaNs in Python
In this article, we will cover how to return the maximum of an array or maximum by ignoring any NaNs in Python using NumPy. ExampleInput: [ -1. -2. nan 1000.] Output: 1000.0 Explanation: maximum value of the array ignoring nans. One approach to use the built-in Python function max(), along with the filter() function and the math.isnan() function fr
4 min read
Highlight the maximum value in last two columns in Pandas - Python
In this article, we will discuss how to highlight the maximum values in Pandas Dataframe. Let's first make a dataframe: Example: C/C++ Code # Import Required Libraries import pandas as pd import numpy as np # Create a dictionary for the dataframe dict = {'Name': ['Sumit Tyagi', 'Sukritin', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 2
2 min read
Convert Strings to Numbers and Numbers to Strings in Python
In Python, strings or numbers can be converted to a number of strings using various inbuilt functions like str(), int(), float(), etc. Let's see how to use each of them. Example 1: Converting a Python String to an int: C/C++ Code # code # gfg contains string 10 gfg = "10" # using the int(), string is auto converted to int print(int(gfg)+2
2 min read
Python Dictionary | Check if binary representations of two numbers are anagram
Given two numbers you are required to check whether they are anagrams of each other or not in binary representation. Examples: Input : a = 8, b = 4 Output : YesBinary representations of bothnumbers have same 0s and 1s.Input : a = 4, b = 5Output : NoCheck if binary representations of two numbersWe have existing solution for this problem please refer
3 min read
Python map function to find row with maximum number of 1's
Given a boolean 2D array, where each row is sorted. Find the row with the maximum number of 1s. Examples: Input: matrix = [[0, 1, 1, 1], [0, 0, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0]] Output: 2 We have existing solution for this problem please refer Find the row with maximum number of 1's. We can solve this problem in python quickly using map() function
1 min read
Python | Pandas series.cummax() to find Cumulative maximum of a series
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Series.cummax() is used to find Cumulative maximum of a series. In cumulative maximum, the length of returned series is same as i
2 min read
Python | Find maximum value in each sublist
Given a list of lists in Python, write a Python program to find the maximum value of the list for each sub-list. Examples: Input : [[10, 13, 454, 66, 44], [10, 8, 7, 23]] Output : [454, 23] Input : [[15, 12, 27, 1, 33], [101, 58, 77, 23]] Output : [33, 101]Get maximum value in each sublist using loop Here, we are selecting each list using a Python
6 min read
Using Counter() in Python to find minimum character removal to make two strings anagram
Given two strings in lowercase, the task is to make them Anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams. Examples: Input : str1 = "bcadeh" str2 = "hea" O
3 min read
Python List Comprehension to find pair with given sum from two arrays
Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to x. Examples: Input : arr1 = [-1, -2, 4, -6, 5, 7] arr2 = [6, 3, 4, 0] x = 8 Output : [(5, 3), (4, 4)] Input : arr1 = [1, 2, 4, 5, 7] arr2 = [5, 6, 3, 4, 8] x = 9 Output : [(1, 8), (4, 5), (5, 4)] We have existing solution for this pr
2 min read
Python | Find missing and additional values in two lists
Given two lists, find the missing and additional values in both the lists. Examples: Input : list1 = [1, 2, 3, 4, 5, 6] list2 = [4, 5, 6, 7, 8] Output : Missing values in list1 = [8, 7] Additional values in list1 = [1, 2, 3] Missing values in list2 = [1, 2, 3] Additional values in list2 = [7, 8] Explanation: Approach: To find the missing elements o
3 min read
Python - Find the Common Keys from two Dictionaries
In this article, we will learn how can we print common keys from two Python dictionaries. We will see that there are multiple methods one can do this task. From brute force solutions of nested loops to optimize ones that trade between space and time to decrease the time complexity we will see different methods to do the task at hand and why they wo
4 min read
Find maximum element of each row in a matrix
Given a matrix, the task is to find the maximum element of each row. Examples: Input : [1, 2, 3] [1, 4, 9] [76, 34, 21] Output : 3 9 76 Input : [1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2] Output : 21 65 56 Approach : Approach is very simple. The idea is to run the loop for no_of_rows. Check each element inside the row and find for the maximum eleme
6 min read
Find the maximum and minimum element in a NumPy array
An array can be considered as a container with the same types of elements. Python has its array module named array. We can simply import the module and create our array. But this module has some of its drawbacks. The main disadvantage is we can't create a multidimensional array. And the data type must be the same. To overcome these problems we use
4 min read
How to find the maximum and minimum value in NumPy 1d-array?
Let's see the various ways to find the maximum and minimum value in NumPy 1d-array. Method 1: Using numpy.amax() and numpy.amin() functions of NumPy library. numpy.amax(): This function returns maximum of an array or maximum along axis(if mentioned). numpy.amin(): This function returns minimum of an array or minimum along axis(if mentioned). Exampl
2 min read
Find Minimum, Maximum, and Average Value of PySpark Dataframe column
In this article, we are going to find the Maximum, Minimum, and Average of particular column in PySpark dataframe. For this, we will use agg() function. This function Compute aggregates and returns the result as DataFrame. Syntax: dataframe.agg({'column_name': 'avg/'max/min}) Where, dataframe is the input dataframecolumn_name is the column in the d
2 min read
Find maximum values & position in columns and rows of a Dataframe in Pandas
In this article, we are going to discuss how to find the maximum value and its index position in columns and rows of a Dataframe. Create Dataframe to Find max values & position of columns or rows C/C++ Code import numpy as np import pandas as pd # List of Tuples matrix = [(10, 56, 17), (np.NaN, 23, 11), (49, 36, 55), (75, np.NaN, 34), (89, 21,
4 min read
Find all Autobiographical Numbers with given number of digits
Given N as the number of digits, the task is to find all the Autobiographical Numbers whose length is equal to N. An autobiographical number is a number such that the first digit of it counts how many zeroes are there in it, the second digit counts how many ones are there and so on. For example, 1210 has 1 zero, 2 ones, 1 two and 0 threes. Examples
8 min read
Find Columns Shared By Two Data Frames
Pandas is the open-source Python library used for Data analysis and manipulation. It is fast, powerful, flexible, and easy to use. In this article, we will discuss how to find columns that are common between two Data Frames. Below is the different approach that can be used to find common columns. Method 1: Using Numpy intersect1d method In this exa
2 min read
Find the longest common prefix between two strings after performing swaps on second string
Given two strings [Tex]a [/Tex]and [Tex]b [/Tex]. Find the longest common prefix between them after performing zero or more operations on string [Tex]b [/Tex]. In each operation, you can swap any two letters.Examples: Input : a = "here", b = "there" Output : 4 The 2nd string can be made "heret" by just swapping characters and thus the longest prefi
6 min read
Given two arrays, find n+m-1 unique sum pairs
Given 2 integer arrays A and B(with no repeated elements in each) of size N and M respectively, form N + M - 1 pairs, each pair having one element from both the arrays, such that the sum of all the pairs is unique. For each pair, print the index of the elements in their respective array. Example: Input: N = 5, M = 3 A = [6, 5, 7, 1, 3] B = [2, 4, 8
3 min read
Find common values between two NumPy arrays
In NumPy, we can find common values between two arrays with the help intersect1d(). It will take parameter two arrays and it will return an array in which all the common elements will appear. Syntax: numpy.intersect1d(array1,array2) Parameter :Two arrays. Return :An array in which all the common element will appear. Example 1: Python Code import nu
1 min read
Find common values between two NumPy arrays
In this article, we are going to discuss how to find out the common values between 2 arrays. To find the common values, we can use the numpy.intersect1d(), which will do the intersection operation and return the common values between the 2 arrays in sorted order. Syntax: numpy.intersect1d(arr1, arr2, assume_unique = False, return_indices = False) P
2 min read
Find the union of two NumPy arrays
To find union of two 1-dimensional arrays we can use function numpy.union1d() of Python Numpy library. It returns unique, sorted array with values that are in either of the two input arrays. Syntax: numpy.union1d(array1, array2) Note The arrays given in input are flattened if they are not 1-dimensional. Let's see examples of how to find union of tw
2 min read
Pandas - Find the Difference between two Dataframes
In this article, we will discuss how to compare two DataFrames in pandas. First, let's create two DataFrames. Creating two dataframes C/C++ Code import pandas as pd # first dataframe df1 = pd.DataFrame({ 'Age': ['20', '14', '56', '28', '10'], 'Weight': [59, 29, 73, 56, 48]}) display(df1) # second dataframe df2 = pd.DataFrame({ 'Age': ['16', '20', '
2 min read
Find the Difference Between Two Rows in Pandas
In this article, we are going to see how to find the difference between two rows in Pandas. Pandas DataFrame is a two-dimensional data structure in tabular form with labeled axes. During data analysis, one might need to compute the difference between two rows for comparison purposes. This can be done using pandas.DataFrame.diff() function. This fun
2 min read
Find four elements that sum to a given value | Two-Pointer approach
Given an array arr of integers of size N and a target number, the task is to find all unique quadruplets in it, whose sum is equal to the target number. Examples: Input: arr[] = {4, 1, 2, -1, 1, -3], target = 1 Output: [[-3, -1, 1, 4], [-3, 1, 1, 2]] Explanation: Both the quadruplets sum equals to target. Input: arr[] = {2, 0, -1, 1, -2, 2}, target
11 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
Python Regex to extract maximum numeric value from a string
Given an alphanumeric string, extract maximum numeric value from that string. Alphabets will only be in lower case. Examples: Input : 100klh564abc365bgOutput : 564Maximum numeric value among 100, 564 and 365 is 564.Input : abchsd0sdhsOutput : 0Python Regex to extract maximum numeric value from a stringThis problem has existing solution please refer
2 min read
Article Tags :
Practice Tags :