Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - max() function
Next article icon

Python - max() function

Last Updated : 30 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Python max() function returns the largest item in an iterable or the largest of two or more arguments.

It has two forms.

  • max() function with objects
  • max() function with iterable

Python max() function With Objects

Unlike the max() function of C/C++, the max() function in Python can take any type of object and return the largest among them. In the case of strings, it returns the lexicographically largest value.

Syntax : max(arg1, arg2, *args[, key]) 

Parameters : 

  • arg1, arg2 : objects of the same datatype
  • *args : multiple objects
  • key : function where comparison of iterable is performed based on its return value

Returns : The maximum value 

Example of Python max() function

We can use max() function to locate the largest item in Python. Below are some examples:

Example 1: Finding the Maximum of 3 Integer Variables

The code initializes three variables with values (var1 = 4, var2 = 8, var3 = 2) and then finds the maximum value among them using the max() function. The result, that is 8, is printed to the screen.

Python3
var1 = 4 var2 = 8 var3 = 2  max_val = max(var1, var2, var3) print(max_val) 

Output
8

Example 2: Finding the Maximum of 3 String Variables

By default, it will return the string with the maximum lexicographic value. In this example, as max() is used to locate the largest item in Python, we are using max() to find maximum out of 3 string variable.

Python3
var1 = "geeks" var2 = "for" var3 = "geek"  max_val = max(var1, var2, var3) print(max_val) 

Output
geeks

Example 3: Finding the Maximum of 3 String Variables According to the Length

We will be passing a key function in the max() method. 

Python3
var1 = "geeks" var2 = "for" var3 = "geek"  max_val = max(var1, var2, var3,             key=len) print(max_val) 

Output
geeks

Example 4: Python max() Exception

If we pass parameters of different datatypes, then an exception will be raised.

Python3
integer = 5 string = "geek"  max_val = max(integer, string) print(max_val) 

Output

TypeError: '>' not supported between instances of 'str' and 'int'

Example 5: Python max() Float

In this example, max() function is used to find and store the maximum value within this list, which is 1.3.

Python3
list = [1.2, 1.3, 0.1] max_value = max(list) print(max_value) 

Output
1.3

Example 6: Python max() Index

In this example, we are using max() to finds and prints the position of the maximum value in a given list.

Python3
# function to find minimum and maximum position in list def maximum(a, n):      # inbuilt function to find the position of maximum     maxpos = a.index(max(a))      # printing the position     print ("The maximum is at position", maxpos + 1)  # driver code a = [3, 4, 1, 3, 4, 5] maximum(a, len(a)) 

Output
The maximum is at position 6

max() Function With iterable In Python

When an iterable is passed to the max() function it returns the largest item of the iterable. 

Syntax : max(iterable, *iterables[, key, default]) 
Parameters : 

  • iterable : iterable object like list or string.
  • *iterables : multiple iterables
  • key : function where comparison of iterable is performed based on its return value
  • default : value if the iterable is empty

Returns : The maximum value. 

Example 1: Finding the Lexicographically Maximum Character in a String

This code defines a string "GeeksforGeeks" and then uses the max() function to find and print the character with the highest Unicode value within the string, which is 's'.

Python3
string = "GeeksforGeeks"  max_val = max(string) print(max_val) 

Output
s

Example 2: Finding the Lexicographically Maximum String in a String List

This code creates a list of strings, "string_list," containing ["Geeks", "for", "Geeks"]. It then uses the max() function to find and print the maximum string based on lexicographic order

Python3
string_list = ["Geeks", "for", "Geeks"]  max_val = max(string_list) print(max_val) 

Output
for

Example 3: Finding the Longest String in a String List

In this code, there is a list of strings, "string_list," containing ["Geeks", "for", "Geek"]. It utilizes the max() function with the key=len argument, which compares the strings based on their lengths.

Python3
string_list = ["Geeks", "for", "Geek"]  max_val = max(string_list, key=len) print(max_val) 

Output
Geeks

Example 4: If the Iterable is Empty, the Default Value will be Displayed

This code initializes an empty dictionary, "dictionary," and then uses the max() function with the default argument set to a default value, which is the dictionary {1: "Geek"}.

Python3
dictionary = {}  max_val = max(dictionary,             default={1: "Geek"}) print(max_val) 

Output
{1: 'Geek'}

Next Article
Python - max() function

Y

Yash_R
Improve
Article Tags :
  • Python
  • Python-Built-in-functions
  • python-basics
Practice Tags :
  • python

Similar Reads

    Enumerate() in Python
    enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
    3 min read
    eval in Python
    Python eval() function parse the expression argument and evaluate it as a Python expression and runs Python expression (code) within the program.Python eval() Function SyntaxSyntax: eval(expression, globals=None, locals=None)Parameters:expression: String is parsed and evaluated as a Python expressio
    5 min read
    filter() in python
    The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. Let's see a simple example of filter() function in python:Example Usage of filter()Python# Function to check if a number is even def even(n): return n % 2 == 0 a = [1
    3 min read
    float() in Python
    Python float() function is used to return a floating-point number from a number or a string representation of a numeric value. Example: Here is a simple example of the Python float() function which takes an integer as the parameter and returns its float value. Python3 # convert integer value to floa
    3 min read
    Python String format() Method
    format() method in Python is a tool used to create formatted strings. By embedding variables or values into placeholders within a template string, we can construct dynamic, well-organized output. It replaces the outdated % formatting method, making string interpolation more readable and efficient. E
    8 min read
    Python - globals() function
    In Python, the globals() function is used to return the global symbol table - a dictionary representing all the global variables in the current module or script. It provides access to the global variables that are defined in the current scope. This function is particularly useful when you want to in
    2 min read
    Python hash() method
    Python hash() function is a built-in function and returns the hash value of an object if it has one. The hash value is an integer that is used to quickly compare dictionary keys while looking at a dictionary.Python hash() function SyntaxSyntax : hash(obj)Parameters : obj : The object which we need t
    6 min read
    hex() function in Python
    hex() function in Python is used to convert an integer to its hexadecimal equivalent. It takes an integer as input and returns a string representing the number in hexadecimal format, starting with "0x" to indicate that it's in base-16. Example:Pythona = 255 res = hex(a) print(res)Output0xff Explanat
    2 min read
    id() function in Python
    In Python, id() function is a built-in function that returns the unique identifier of an object. The identifier is an integer, which represents the memory address of the object. The id() function is commonly used to check if two variables or objects refer to the same memory location. Python id() Fun
    3 min read
    Python 3 - input() function
    In Python, we use the input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function converts it into a string.Python input() Function SyntaxSyntax: input(prompt)Parameter:Prompt: (optional
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences