[Tutor] __getitem__

Alan Gauld alan.gauld at yahoo.co.uk
Wed Nov 23 17:25:08 EST 2016


On 23/11/16 12:25, monikajg at netzero.net wrote:

> I have two questions in regards to below code:
> 1. largest is a list, not a list of lists. 
> [('deit', 4), ('acer', 3), ('aceilmr', 2), ('arst', 2)]
> so why when I do largest[0] I get the whole list again, 

I don't know you will need to show us some real code.
Ideally input at the >>> prompt.

> 2. largest = [sorted(analist, key=lambda analist: analist[1], reverse=True)]
> brings back the same result as:
> largest = [sorted(analist, key=lambda d: d[1], reverse=True)]
> and the same result as:
> largest = [sorted(analist, key=lambda x: x[1], reverse=True)]

Yes because it doesn't matter what you call the parameter of the lambda,
it's like any other function:

def add2(x): return x+2

def add2(y): return y+2

def add2(z): return z+2

All of these functions are identical they always do the same
regardless of what you call the parameter. Remember a lambda
is just a shortcut for a function

key = lambda d: d[1]

is identical to

def key(d): return d[1]

and

key = lambda analist: analist[1]

is identical to

def key(analist): return analist[1]

Just like the add2() examples it doesn't matter what
name you use for the parameter.

> ...but where does it get the x, what is the value of x? 

See my other post about how sorted() works.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list