0Pricing
DSA Interview Prep · Lesson

Functions, Closures, and Lambda

Define reusable helper functions, use default arguments, and apply lambda expressions to sorting and functional patterns in interview problems.

Defining Functions in Python

Functions are first-class in Python: you can pass them around, return them, and store them. Well-named helpers make interview code readable. Handle edge cases first.

def is_palindrome(s: str) -> bool:
    '''Return True if s reads the same forwards and backwards.'''
    s = s.lower()
    return s == s[::-1]

print(is_palindrome('Racecar'))  # True
print(is_palindrome('hello'))    # False

# Functions as values
checks = [is_palindrome]
print(checks[0]('level'))  # True

Default and Keyword Arguments

Defaults let callers skip arguments. But never use a mutable default like a list — all callers share it. The fix: default to None and create the list inside. See the code.

# WRONG: shared mutable default
def bad_append(val, lst=[]):
    lst.append(val)
    return lst

print(bad_append(1))  # [1]
print(bad_append(2))  # [1, 2]  surprise!

# CORRECT: use None sentinel
def good_append(val, lst=None):
    if lst is None:
        lst = []
    lst.append(val)
    return lst

print(good_append(1))  # [1]
print(good_append(2))  # [2]

All lessons in this course

  1. Lists, Tuples, and Slicing
  2. Dictionaries and Sets in Python
  3. Comprehensions and Built-ins
  4. Functions, Closures, and Lambda
← Back to DSA Interview Prep