Origami Magic
Hoppy needs to double the value of all magic stones in the warehouse.
The Archmage says: "Don't set up the heavy drafting table (def) for such a tiny task. Use Origami Magic (Lambda)."
Fold it, cast it, toss it. Lightweight and fast.
The Tiny Spell (Lambda)
# Traditional Way (Too heavy) def double(x): return x * 2 # Lambda Way (Lightweight) double = lambda x: x * 2
Syntax: lambda input: output.
Note: It automatically returns the result. No return keyword needed.
Your Mission
1
Create Tiny Spell
Create a lambda function named square that calculates the square (x * x).
2
Test It
Print square(5). It should output 25.
3
Advanced Use (Map)
We have a list nums = [1, 2, 3, 4].
Use list(map(square, nums)) to square them all at once, and print the result.
Power of Map
map(spell, list): Casts the spell on EVERY item in the list. A powerful tool for data processing!
Suggested SolutionExpandCollapse
ExpandCollapse
Solution:
nums = [1, 2, 3, 4] # Create lambda square = lambda x: x * x print(square(5)) # 25 # Use with map print(list(map(square, nums))) # [1, 4, 9, 16]
Advanced TipsWant more? Click to expandClick to collapse
F. Bridge to Reality
- Origami Magic = Anonymous Function.
- In Python,
lambdais limited to one expression. - It's most commonly used with higher-order functions like
map()(mapping),filter()(filtering), orsorted()(sorting).- Example:
sorted(items, key=lambda x: x['price'])— sort by price.
- Example:
Loading...
Terminal
Terminal
Ready to run...