Working With Iterables

Aggregate and Analyze Iterables

This tutorial recaps what we've learned about Python iterables, such as strings and lists. We'll use built-in functions like min(), max(), and sum() to extract information from these iterables.


Let's talk about iterables.

An iterable is a Python object that can be iterated over, meaning you can traverse through all the elements in the object.

You already know the most common Python iterables: strings, lists, and tuples:

Python

Remember that you can loop through the elements in all of these iterables:

Python
Output

Sometimes, you'll need to get some general information about these iterables.

For example, you might want to get the maximum value of a list of numbers.

You could do this using a for-loop:

Python
Output

While this approach works, it involves quite a bit of code. Fortunately, Python offers built-in functions that can simplify these tasks significantly.

The max() function returns the largest item in an iterable.

Here's how you can use it:

Python
Output

Similarly, the min() function returns the smallest item in an iterable.

Python
Output

If we apply min() and max() to a string, we get the smallest and largest character based on their Unicode values.

This behavior can be useful when you want to find the 'smallest' or 'largest' character in a string based on alphabetical order.

Let's see how this works:

Python
Output

Now, let's test your understanding!


What will be the output?

Python

What will be the output?

Python

The sum() function returns the sum of all items in an iterable, such as a list of numbers.

Here's how you can use it:

Python
Output

However, while min() and max() work with strings, the sum() function is only for numerical iterables.


What will be the output?

Python

What will be the output?

Python