# The Python max() function explained - with examples

**URL:** <https://forum.freecodecamp.org/t/the-python-max-function-explained-with-examples/19205>\
**Category:** freeCodeCamp Contributors\
**Tags:** guide\
**Created:** [July 11, 2016, 2:49am UTC](https://forum.freecodecamp.org/t/the-python-max-function-explained-with-examples/19205 "2016-07-11T02:49:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![camperbot](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/camperbot/32/18364_2.png) [@camperbot](https://forum.freecodecamp.org/u/camperbot)\
**Post date:** [July 11, 2016, 2:49am UTC](https://forum.freecodecamp.org/t/the-python-max-function-explained-with-examples/19205/1 "2016-07-11T02:49:48Z")

</div>

`max()` is a built-in function in Python 3. It returns the largest item in an iterable or the largest of two or more arguments.

## Arguments

This function takes two or more numbers or any kind of iterable as an argument. While giving an iterable as an argument, we must make sure that all the elements in the iterable are of the same type. This means that we cannot pass a list which has both string and integer values stored in it.  
Syntax:  
\*max(iterable, _iterables[,key, default])_  
\*max(arg1, arg2, _args[, key])_

Valid Arguments:

```auto
max(2, 3)
max([1, 2, 3])
max('a', 'b', 'c')

```

Invalid Arguments:

```auto
max(2, 'a')
max([1, 2, 3, 'a'])
max([])

```

## Return Value

The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned. If the iterable is empty and default is not provided, a `ValueError` is raised.

## Code Sample

```auto
print(max(2, 3)) # Returns 3 as 3 is the largest of the two values
print(max(2, 3, 23)) # Returns 23 as 23 is the largest of all the values

list1 = [1, 2, 4, 5, 54]
print(max(list1)) # Returns 54 as 54 is the largest value in the list

list2 = ['a', 'b', 'c']
print(max(list2)) # Returns 'c' as 'c' is the largest in the list because c has ascii value larger then 'a' ,'b'.

list3 = [1, 2, 'abc', 'xyz']
print(max(list3)) # Gives TypeError as values in the list are of different type

#Fix the TypeError mentioned above first before moving on to next step

list4 = []
print(max(list4)) # Gives ValueError as the argument is empty

```

![:rocket:](https://forum.freecodecamp.com/images/emoji/twitter/rocket.png?v=2 ":rocket:") [Run Code](https://repl.it/CVok)

---

<div class="post-metadata">

**Author:** ![kevcomedia](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/kevcomedia/32/125737_2.png) [@kevcomedia](https://forum.freecodecamp.org/u/kevcomedia)\
**Post date:** [August 7, 2017, 1:44am UTC](https://forum.freecodecamp.org/t/the-python-max-function-explained-with-examples/19205/2 "2017-08-07T01:44:19Z")

</div>

Closed on August 7, 2017, 1:44am UTC


