D. Hartley wrote:
Re: the key discussion: that was very helpful, thank you! So if I had
a list of tuples, and I wanted to use the "key" function to arrange
the list of tuples by the second tuple item, I would define a function
that returns the second tuple item, and then do key=find_second()? or
could i just do key=[1]?

Close but not quite. You define a function that takes one argument (the tuple) and returns the second item:
def find_second(tup):
return tup[1]


then use key=find_second <- note NO parentheses, you are passing a reference to the function as the key parameter. If you write key=find_second() you are calling find_second and using the result as the key parameter. which will not do what you want.

BTW (Denise don't worry if you don't understand this, I thought some of the other readers might be interested) the operator module defines a function that *creates* a function to get items. So you could use this:
import operator
lst.sort(key=operator.itemgetter(1))


In this case you do call the itemgetter function; its return value is itself a 
function of one argument.

 >>> import operator
 >>> get1 = operator.itemgetter(1)
 >>> get1([1,2,3])
2
 >>> get1('abc')
'b'
 >>> get1( (1,2,3) )
2

Kent

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to