Python Expressions: Advanced
Airbnb's data infrastructure team processes over 100 million searches per day across more than 220 countries, and they use Python decorators to add logging, caching, and retry logic to thousands of pipeline functions without modifying a single line of each function's core logic. Instead of copying the same instrumentation code into every function, Airbnb engineers write one decorator and apply it with a single line, keeping the codebase dry and every function focused on exactly one responsibility. Context managers and generators give their pipelines the same discipline around resource cleanup and memory efficiency, ensuring that database connections close and large datasets stream without ever being fully loaded into memory. The advanced syntax patterns in this lesson are the tools that let engineers at Airbnb-scale organizations build systems that are both powerful and maintainable.
Multiple Assignment
Unpack values into variables efficiently
Swapping Without Temp Vars
Reverse an Array In-Place
Cycle Detection (Floyd's Algorithm)
Parallel Assignment
Sequence Unpacking
Unpack any iterable into variables. The number of variables must match the number of elements (unless using the * operator):
Extended Unpacking with *
The * operator captures "the rest" of an iterable. Only one starred expression is allowed per unpacking:
> Python can swap two variables in one line. Compare the simultaneous swap to step-by-step assignment.
a = 1 b = 2 print(a, b)
Short-circuit Evaluation
Skip unnecessary checks automatically
Python's and and or operators don't return True/False. They return the value that determined the result. This enables powerful patterns for defaults and guards.
Returns 0, "hello", and [] respectively. and returns first falsy, or last if all truthy.
Returns "hello", {}, and "hi" respectively. or returns first truthy, or last if all falsy.
Default Values Pattern
Use or to provide fallback values when a variable might be falsy:
Guard Clauses
- if x and x.expensive():
- if i < len(arr) and arr[i]:
- if node and node.val > 0:
- if x.expensive() and x:
- if arr[i] and i < len(arr):
- if node.val > 0 and node:
> A function uses short-circuit evaluation to safely provide a default when a variable is None or empty. Pick the correct logical operator to return the first truthy value as a fallback, and the correct operator to guard against calling a method on None.
name = "" display = name "Guest" print(display) data = None result = data data.upper() print(result)
Short-circuit evaluation is more than a performance trick; it is a safety mechanism. The pattern node and node.val is so common in linked list problems that it becomes second nature.
The or default pattern is equally pervasive: result = value or default is Python's concise way to provide a fallback when a value may be absent or empty.
Truthy and Falsy Values
Predict which values act as true or false
Every Python object has a boolean value. In boolean contexts (if, while, and, or, not), Python implicitly converts values. Knowing what's falsy lets you write cleaner conditions.
Idiomatic Boolean Checks
- if items:
- if not name:
- while stack:
- if node:
- if len(items) > 0:
- if name == "":
- while len(stack) > 0:
- if node != None:
> Some values look truthy but are actually falsy. Pick a value to test whether Python treats it as True or False.
val = if val: print("truthy") else: print("falsy")
None vs Falsy
When you need to distinguish None from other falsy values (0, "", []), use is None or is not None:
is None and is not None instead of == None. The "is" operator is faster and more explicit about identity comparison.Ternary Expressions
Write conditional assignments in one line
Interview Applications
When NOT to Use Ternary
- x if condition else y
- a if a > b else b
- val if val else default
- a if x else b if y else c if z else d
- f(x) if g(y) else h(z) if i(w) else j(k)
- Long expression if complex_condition else other_long
> A ternary expression picks one of two values based on a condition. Pick a value for x to see which branch runs.
x = result = "positive" if x > 0 else "not positive" print(result)
Walrus Operator (:=)
Assign and test a value simultaneously
The walrus operator := (officially "assignment expression") assigns a value AND returns it in the same expression. It eliminates redundant variable assignments and repeated computations.
Named "walrus" because := looks like a walrus with tusks. Added in Python 3.8.
Avoiding Repeat Computation
In List Comprehensions
> This list comprehension has a duplicated keyword that causes a syntax error. Find and remove the extra tile.
SyntaxError: invalid syntax
Interview Applications
Chained Comparisons
Interview Pattern Summary
You are in a coding interview. The problem is: given a sorted array and a target, return the index of the target or -1 if not found. You have 15 minutes.
| detail | value |
|---|---|
| array_size | up to 10^6 |
| time_limit | O(log n) |
The array is sorted and the expected complexity is O(log n). What approach do you use?
- Initialize pointers with multiple assignment, not separate lines
- Use chained comparisons for bounds: 0 <= i < n
- Guard with short-circuit:
ifnodeandnode.val - Prefer ternary for simple one-line conditionals
- Use is None instead of == None
> You are a data engineer at Netflix refactoring a real-time event processing script to be as concise as possible without sacrificing on-call readability. Every expression must do exactly one job, and the team requires that all assignment, evaluation, and branching happen in the fewest lines.
or 1000 supply a safe default without an explicit None check.:= reads the next batch and assigns it inside the while condition, collapsing fetch-and-check into a single expression.and/or return actual values, not booleans; enable guards and defaultsNone, False, 0, "", [], {}, (). Everything else is truthy:= assigns and returns in one expressionPython Expressions: Advanced
Patterns for technical interviews
- Category
- Python
- Difficulty
- advanced
- Duration
- 40 minutes
- Challenges
- 0 hands-on challenges
Topics covered: Multiple Assignment, Short-circuit Evaluation, Truthy and Falsy Values, Ternary Expressions, Walrus Operator (:=)
Lesson Sections
- Multiple Assignment
Python allows assigning multiple variables simultaneously. This isn't just syntactic sugar; it's essential for many algorithmic patterns. Understanding how it works internally helps you avoid subtle bugs. Swapping Without Temp Vars In most languages, swapping two variables requires a temporary variable. Python evaluates the right side completely before assigning, enabling direct swaps: This works because Python evaluates (b, a) as a tuple first, THEN unpacks it into (a, b). This pattern is criti
- Short-circuit Evaluation
Default Values Pattern If the left value is falsy, the right value is used as default. Guard Clauses Short-circuiting prevents errors by skipping expressions that would fail. The second expression is never evaluated if the first determines the result: The second expression is never evaluated if the first determines the result. Order matters in guard clauses. Always put the cheaper/safer check first:
- Truthy and Falsy Values
Everything else is truthy. This includes things that might surprise you: All are True. Non-empty strings, non-empty containers, and non-zero numbers are truthy. Idiomatic Boolean Checks Pythonic code uses truthy/falsy values directly instead of explicit comparisons: These truthy/falsy patterns appear constantly in algorithmic code. Here is a valid parentheses checker using stack truthiness: Tree inorder traversal: None vs Falsy Problem: 0 is a valid return value but falsy. Wrong check: Correct c
- Ternary Expressions (concepts: pyTernary)
Python's ternary operator lets you write if-else logic as an expression. This is invaluable for inline conditionals, especially in list comprehensions and return statements. In return statements and list comprehensions: Interview Applications Ternary expressions appear constantly in algorithmic solutions for handling edge cases and making decisions inline: When NOT to Use Ternary Ternary expressions prioritize conciseness, but readability matters more. Avoid nesting and complex conditions: Bad -
- Walrus Operator (:=)
Without walrus - assign then test: With walrus - assign and test simultaneously: Avoiding Repeat Computation The walrus operator shines when you need to use a computed value in both a condition and the body: In List Comprehensions Walrus is particularly useful in list comprehensions when both the condition and the value need a computed result: Compute once, use twice in the comprehension. Interview Applications In interviews, walrus can make solutions more concise, but use it judiciously. Clarit