Lists in python

a=[‘py’,‘snake’,‘pro’,‘python’]
print(min(a,key=len))

Wat is the use of " key = len"

So a min function usually returns minimum value among the argument supplied to the function. Finding a minimum in terms of numbers is not a big deal as they have their respective values For example , everyone will agree when I say 2 is less than 100. But for strings, how would you compare them?
So here comes the key parameter. In your example you set a key to len, that means it ll compare based on the length of string and return the string with minimum length. which is ‘py’ in this case

1 Like

Can you please list some other keys that can be used by min

The Python documentation is pretty good for this sort of thing.

https://docs.python.org/3/library/functions.html#min

Hmm, less so in this case though. The tricky part is that since min works on any iterable, you can define all sorts of keys for lists of user defined objects.

Here’s a fun example off of Stack Overflow.

def winner():
    w = max(players, key=lambda p: p.totalScore)

In this case the key is a function. There is no comprehensive list since the key can be any way to find the “smallest” data.

1 Like

Your example is wrong.

It should be:

def winner():
    w = max(players, key=lambda p: p['totalScore'])

And even then, I’d recommend using itemgetter over lambda.

from operator import itemgetter
def winner():
    w = max(players, key=itemgetter('totalScore'))

Python supports dot notation. The example is fine. Itemgetter will also work.

dot notation only works with attributes, not items.

Who said anything about a dictionary? Sure, you have to use a name space for the example to work for a dictionary, but nobody was talking about dictionaries. Dot notation works fine with objects. An array of dictionaries would be a bit strange in my example, as they would all need to have the ‘totalScore’ key.

Which is very common after you query a database.

Maybe. Without any context specifically using a dictionary, my example is fine. You can use dot notation with objects and in this case I would expect an array of things with matching keys to be objects. If you must use a dictionary, then yours works.