len(), min() and max() in Python

In this article, we would discuss three Python functions – len(), min() and Max() with appropriate examples.

First and foremost, all the above three are built-in functions. We will start with len() now –

I. len() – The function is used to find the number of elements in a sequence. We will see here, how it works for a list and string.

First, for a list. Let’s say we have a list, x

x=["a","b","c","d"]

To get the number of elements –

print(len(x))

It would return with –

4

But, for a string if we do the same –

x="abcde"
print(len(x))

It would return with –

5

So, for a string it would count the number of characters. Similarly, we can do for other sequences like tuples, dict etc.

II. min() – through min() function, we can identify the lowest value in a sequence. Again, we would perform following operations to understand how it’s different for integers and strings.

Let’s say we have a list, x

x=[5,2,4,7,8]

To get the minimum value –

print(min(x))

It would return with –

2

Now, consider the scenario wherein we have string values instead of integers.

x=["bce", "tre", "afm"]

For the minimum value –

print(min(x))

It would return with –

afm

So, we understood from here that min() is comparing the value alphabetically. But, what if two string values start with the same character as shown below –

x=["agm", "afm"]
print(min(x))

This time around it would again return with –

afm

Reason being is, once the interpreter identifies that it has got same character value at the beginning. Thereafter, it provides the outcome based on the character following it. That’s how we got afm as the output.

III. max() – max() function is used to identify the maximum value in sequence. We will continue with the example we have used for min() function.

x=[5,2,4,7,8]
print(max(x))

The maximum value –

8

For the string values –

x=["agm", "afm"]
print(max(x))

Notice that, this time the output would be –

agm

In conclusion, though we haven’t discussed examples using different sequences like dict, tuple etc. But, most of it is self-explanatory once you understand how things work.