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:
Remember that you can loop through the elements in all of these iterables:
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:
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:
Similarly, the min() function returns the smallest item in an iterable.
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:
Now, let's test your understanding!
What will be the output?
What will be the output?
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:
However, while min() and max() work with strings, the sum() function is only for numerical iterables.
What will be the output?
What will be the output?