๐ง
STUDENT NOTES ยท DAY 10 OF 24
Shape-Shifting Spells ๐ง
Functions that accept ANY number of things, and tiny one-line spells called lambdas.
1*args โ take as many as you like
๐
Py: What if your function should add 2 numbersโฆ or 5โฆ or 50? *args scoops ALL of them into a tuple.
2**kwargs โ take named things
๐ฆ
Professor Hoot: *args collects plain values (a tuple); **kwargs collects name=value pairs (a dictionary โ full story tomorrow!).
3lambda โ the one-line spell
Lambda tester: (lambda x: x * 2 + 1)(x)
x = 4
(lambda x: x * 2 + 1)(4) โ 9
4Where lambdas shine: sorting with a key
๐ค
Bittu: key=len tells my sorter: judge each word by its LENGTH, not alphabet. Lambdas make great judges.
5Quick quiz! ๐ง
Inside def f(*args), what type is args?
๐ก *args packs the extra arguments into a tuple.
What is (lambda a, b: a + b)(3, 4)?
๐ก A nameless mini-function: 3 + 4 = 7, used on the spot.
6Your mission ๐
Mission 1: Write biggest(*nums) that returns max(nums). Call it with 3, then 6 numbers.
Mission 2: Sort ["kiwi", "banana", "fig"] by length using key=len.
Mission 3: Write a lambda that tells if a number is even: lambda n: n % 2 == 0.
Day 10 done โ half the course conquered soon! ๐ง
Next: dictionaries โ the register that maps names to marks.
Go to Day 11: Dictionaries โ