Using min() and max() With Comprehensions and Generators
This comes in handy when you need to transform the input data right before finding the minimum or maximum transformed value. When you feed a list comprehension into
max(), the resulting value will come from the transformed data rather than the original data.
The second call to
min() takes a list comprehension as an argument. This comprehension transforms the original data in
letters by applying the
.lower() method to each letter. The final result is the lowercase
"a", which isn’t present in the original data.
Note that using
max() with a list comprehension is similar to using the
key argument. The main difference is that with comprehensions, the final result is a transformed value, while with
key, the result comes from the original data.
In both examples,
.lower() to somehow modify the comparison criteria. The difference is that the comprehension actually transforms the input data before doing the computation, so the resulting value comes from the transformed data rather than from the original. List comprehensions create a complete list in memory, which is often a wasteful operation.
This is especially true if you don’t need the resulting list in your code anymore, which could be the case with
max(), so it’s always more efficient to use a generator expression instead.
02:21 main syntax difference is that a generator expression uses parentheses instead of square brackets. Because a function call already requires parentheses, you just need to remove the square brackets from your comprehension-based examples, and you are good to go.
Unlike list comprehensions, generator expressions yield items on demand, which makes them memory efficient. In the next part of the course, you’ll take a look at practical examples of
max() in action.
Become a Member to join the conversation.