AI summary by TwinMind
Lecture 9: Lambda Functions, Tuples, and Lists
MIT OpenCourseWare
45m 26s
Lambda Functions Introduction
- Wrap up functions discussion by introducing Lambda functions for creating anonymous functions
- Complete exploration of function creation
- Introduce new object types: tuples and lists
Review of Functions as Objects
- Previous example:
applyfunction that takes another function as parameter - Functions in Python are objects with names
- Can use functions as parameters to other functions
applyfunction assumescriteriaparameter is function taking number, returning Boolean- Example:
is_evenfunction used as parameter - simple one-liner function
Lambda Function Syntax and Structure
- Lambda functions create anonymous functions for simple tasks
- Don't need full function definition for simple operations
- Syntax:
lambda x: x % 2 == 0equivalent tois_evenfunction - Components:
lambdakeyword starts anonymous functionxrepresents parameters (comma-separated for multiple):separator- Function body (no return keyword needed)
- Use case: quick functions used only once, no name needed
Lambda Function Examples and Usage
is_fivefunction equivalent:lambda x: x == 5- Can call directly:
(lambda x: x % 2 == 0)(8) - Useful when don't want to reuse functionality
- No way to access body later - must copy/paste entire lambda expression
Tracing Lambda Function Execution
- Example:
do_twice(3, lambda x: x**2) - Step-by-step environment creation:
- Global environment with
do_twicefunction do_twiceenvironment:n=3,fn=lambda x: x**2- First lambda call:
x=3, returns9 - Second lambda call:
x=9, returns81 - Final return:
81
- Global environment with
Introduction to Compound Data Types
- Previous data types: integers, floats, booleans, None, strings
- Strings as compound data type - sequence of characters
- Could index, slice, get length of strings
- New compound types: tuples and lists
- Operations similar to strings
Tuples Definition and Properties
- Indexable ordered sequences of objects
- Sequence of any kind of objects (not just characters)
- Ordered sequence - objects have positions
- Indexable - can grab elements at specific indices
Tuple Creation Syntax
- Empty tuple:
() - Single element:
(4,)- comma required to differentiate from precedence parentheses - Multiple elements:
(2, 'MIT', 3)- comma-separated - Can mix different object types
- Different from function calls (no function name before parentheses)
Tuple Operations
- Indexing:
t[0]gets first element - Concatenation:
+operator joins tuples - Slicing: similar to strings
- Length:
len(t)returns number of elements - Max/Min/Sum:
max(t),min(t),sum(t) - Immutable: cannot modify elements after creation (like strings, integers)
Nested Tuples
- Tuple elements can be other tuples
- Example:
seq = (2, 'a', 4, (1, 2)) - Length counts top-level elements only:
len(seq) = 4 - Chained indexing:
seq[3][0]gets first element of nested tuple - Can iterate over tuple elements directly:
for e in seq:
Tuple Applications - Variable Swapping
- Traditional swapping requires temporary variable
- Tuple assignment enables one-line swap:
x, y = y, x - Right side evaluated first, then values assigned to left side variables
- Very useful shorthand for multiple variable assignments
Returning Multiple Values with Tuples
- Functions can only return one object
- Tuples are single objects containing multiple values
- Example:
quotient_remainder(x, y)returns(q, r) - Can unpack return:
quote, rem = quotient_remainder(5, 2) - Enables functions to return multiple calculated values
Variable Arguments with Tuples
- Functions can take variable number of arguments using
*args - Star notation converts arguments to tuple automatically
- Example:
mean(*args)function - Can call with any number of arguments:
mean(1,2,3,4,5,6)ormean(6,0,9) - Function treats
argsas tuple of all parameters
Lists Introduction
- Similar to tuples but use square brackets:
[] - Empty list:
[] - Single element:
[4]- no comma needed - Multiple elements:
[2, 'MIT', 3] - Most operations identical to tuples
- Key difference: mutability (covered in next lecture)
Iterating Over Lists and Tuples
- Can iterate over elements directly instead of indices
- More pythonic:
for i in L:vsfor i in range(len(L)): - Loop variable takes on actual values, not indices
- Easier to read and debug
- Works with different element types (numbers, strings, etc.)
- Recommend writing comments about loop variable values for clarity
