Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

Using min() and max() With Comprehensions and Generators

00:00 Using min() and max() With Comprehensions and Generator Expressions. You can also call min() or max() with a list comprehension or generator expression as an argument.

00:11 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 min() or max(), the resulting value will come from the transformed data rather than the original data.

00:41 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.

00:57 You can also see this in action with max().

01:07 Note that using min() or 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.

01:32 In both examples, min() uses .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.

01:55 This is especially true if you don’t need the resulting list in your code anymore, which could be the case with min() and max(), so it’s always more efficient to use a generator expression instead.

02:07 The syntax for generator expressions is almost the same as for list comprehensions. The

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.

02:37 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 min() and max() in action.

Become a Member to join the conversation.