Paul's Python CoursePPC

lambda, a function on one line

Not met yet

lambda makes a small function with no name: lambda item: item[1] takes item and gives back item[1]. There's no return; whatever comes after the colon is what comes back. It's for places that need a function once, like key= in sorted. If it needs a name, or more than one line, write a def.

Try it

main.py
stock = [("figs", 3.20), ("leeks", 0.90), ("plums", 2.10)]
print(sorted(stock, key=lambda item: item[1]))

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks a lambda needs the return keyword, like a def.
  • Thinks a lambda runs as soon as it is written, rather than when it is called.

Where it comes up