Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

min() and max() with key

You know max() and min() from the lesson on loops: they give you the largest and the smallest value of a list. They take key too. Then they compare the elements by what the key function returns, as sorted() does, and return the element itself:

words = ["cherry", "fig", "banana", "kiwi"]
print(max(words, key=len))
print(min(words, key=len))
print(max(words))
cherry
fig
kiwi

The longest word is "cherry". "banana" is just as long, but when several elements have the same largest key, max() returns the first of them. Without key, max() compares the texts themselves, so it returns the last one in alphabetical order, "kiwi".

With a key function of your own, you find the best player:

def by_score(player):
    return player[1]

results = [("Anna", 12), ("Tom", 7), ("Eva", 15)]
best = max(results, key=by_score)
print(best)

name, score = best
print(f"The winner is {name} with {score} points.")
('Eva', 15)
The winner is Eva with 15 points.

max() returns Eva's whole tuple, and you can unpack it into two variables as usual. sorted(results, key=by_score, reverse=True)[0] would give you the same tuple, but max() doesn't have to sort the whole list. It goes through it once, like the loop for the largest value from the lesson on loops, and it says straight away what you're looking for.

A list of dictionaries and a dictionary's .items() work the same way: max(scores.items(), key=by_score) is the pair with the largest value. Only an empty list has no largest element: max([]) ends with ValueError: max() iterable argument is empty.

Instructions

  1. 1

    Print the longest word in sentence. Split the sentence into a list of words with .split(), and give the list to max() with key=len. The output should be beginners. Leave the line with the sentence as it is: the exercise also tries your program with another sentence.

  2. 2

    Write a function by_price(product) that returns the price of one product. Use it with min() and max() to print the names of the cheapest and the most expensive product: Cheapest: pencil and Most expensive: backpack. Leave the products as they are: the exercise also tries other prices.

Back

8/9

  1. 1. Sorting with sorted()
  2. 2. The .sort() Method
  3. 3. Quiz: sort() or sorted()?
  4. 4. From the Largest
  5. 5. Sorting by Another Rule
  6. 6. Your Own Key
  7. 7. Quiz: Sorting
  8. 8. min() and max() with key
  9. 9. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.