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:
str = 'iterable'
lst = [1, 2, 3]
tpl = (1, 2, 3)
dict = {'a': 1, 'b': 2, 'c': 3}
Remember that you can loop through the elements in all of these iterables:
def traverse(iter):
for item in iter:
print(item)
traverse('iter')
traverse([1, 2, 3])
traverse((1, 2, 3))
traverse({'a': 1, 'b': 2, 'c': 3})
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:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
max_value = 0
for number in numbers:
if number > max_value:
max_value = number
print('The maximum value is:', max_value)
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:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
max_value = max(numbers)
print('The maximum value is:', max_value)
Similarly, the min()
function returns the smallest item in an iterable.
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
min_value = min(numbers)
print('The minimum value is:', min_value)
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:
text = 'hello'
print('The minimum character is:', min(text))
print('The maximum character is:', max(text))
Now, let's test your understanding!
What will be the output?
nums = [10, 5, 20]
min_num = min(nums)
max_num = max(nums)
print(min_num, max_num)
What will be the output?
text = 'abc'
min_char = min(text)
max_char = max(text)
print(min_char, max_char)
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:
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print('The total sum is:', total)
However, while min()
and max()
work with strings, the sum()
function is only for numerical iterables.
What will be the output?
numbers = (2, 4, 6, 8)
total = sum(numbers)
print(total)
What will be the output?
mixed_values = [1, 'two', 3]
max_value = max(mixed_values)
print(max_value)