I am reading about lambda expressions at https://docs.python.org/2/tutorial/controlflow.html#lambda-expressions, and I do not understand where sort() gets its parameters from here. It shows:
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
where "pair: pair[1]" was not named before being used in lambda. I also did:
In [23]: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
In [24]: pairs.sort(key=lambda x: x[1])
In [25]: pairs
Out[25]: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
In [26]: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
In [27]: pairs.sort(key=lambda randomname: randomname[1])
In [28]: pairs
Out[28]: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
In [29]: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
In [30]: pairs.sort(key=lambda randomname: mismatch[1])
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
...
NameError: global name 'mismatch' is not defined
This shows me that the lambda can take any random parameter name, and knows to get the [1] spot from the pairs list.
I also do not understand what "key" is even taking, as the docs say it takes a function of one argument, then use key=str.lower
as an example. But using their exact example fails:
student_tuples
Out[55]: [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ('John', 'b', 5)]
In [60]: sorted(student_tuples, key=str.lower)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-60-86a57d272cfb> in <module>()
----> 1 sorted(student_tuples, key=str.lower)
TypeError: descriptor 'lower' requires a 'str' object but received a 'tuple'
In [61]: sorted(student_tuples, key=str.lower())
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-61-983b5ca19cdb> in <module>()
----> 1 sorted(student_tuples, key=str.lower())
TypeError: descriptor 'lower' of 'str' object needs an argument
Even when giving it strings as an iterable, the str.lower method fails:
In [68]: strings
Out[68]: ['str', 'str2', 'str3']
In [69]: sorted(strings, str.lower)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-69-271d28a2618f> in <module>()
----> 1 sorted(strings, str.lower)
TypeError: lower() takes no arguments (1 given)
My question is
how did the lambda function know to assign the position in the current iterable (calling the iterable itself gets
TypeErro:'tuple' object is not callable
)What is key actually taking, and does it only take lambdas?
Thank you