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

Daily Life
Interviews

Unpack values into variables efficiently

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:
1a, b = b, a
This works because Python evaluates (b, a) as a tuple first, THEN unpacks it into (a, b).
This pattern is critical for in-place array algorithms like reversing, rotating, or partitioning:
//

Reverse an Array In-Place

1def reverse(arr):
2 left, right = 0, len(arr) - 1
3 while left < right:
4 arr[left], arr[right] = arr[right], arr[left]
5 left += 1
6 right -= 1
//

Cycle Detection (Floyd's Algorithm)

1slow, fast = head, head
2while fast and fast.next:
3 slow, fast = slow.next, fast.next.next
4 if slow == fast:
5 return True

Parallel Assignment

Initialize multiple variables on one line. All values on the right are evaluated before any assignment occurs:
1left, right = 0, len(arr) - 1
2count, total = 0, 0
3prev, curr = None, head
Two pointers pattern:
1i, j = 0, 0
2while i < len(a) and j < len(b):
3 if a[i] < b[j]:
4 result.append(a[i])
5 i += 1
6 else:
7 result.append(b[j])
8 j += 1
TIP
All expressions on the right side are evaluated BEFORE any assignments happen. This is why a, b = b, a works. The tuple (b, a) is fully constructed first.

Sequence Unpacking

Unpack any iterable into variables. The number of variables must match the number of elements (unless using the * operator):

1x, y, z = [1, 2, 3]
2first, second, third = "abc"
Unpacking with enumerate and dictionary items:
1for i, val in enumerate(arr):
2 print(f"Index {i}: {val}")
3
4for key, value in d.items():
5 process(key, value)
Unpacking coordinates:
1point = (3, 4)
2x, y = point
3distance = (x**2 + y**2) ** 0.5

Extended Unpacking with *

The * operator captures "the rest" of an iterable. Only one starred expression is allowed per unpacking:

1first, *rest = [1, 2, 3, 4, 5]
2print("first:", first)
3print("rest:", rest)
4
5first, *middle, last = [1, 2, 3, 4, 5]
6print("first:", first, "middle:", middle, "last:", last)
>>>Output
first: 1
rest: [2, 3, 4, 5]
first: 1 middle: [2, 3, 4] last: 5
The * operator captures "the rest" into a list. It can appear at the beginning, middle, or end.
Useful for recursive patterns:
1def recursive_sum(first, *rest):
2 if not rest:
3 return first
4 return first + recursive_sum(*rest)
Fill in the Blank

> Python can swap two variables in one line. Compare the simultaneous swap to step-by-step assignment.

a = 1
b = 2

print(a, b)
Multiple assignment is one of Python's most practical features. It keeps related initializations on one line, making the intent clear at a glance.
Whenever you see a swap, a two-pointer initialization, or a loop like "for i, val in enumerate(...)", multiple assignment is doing the work behind the scenes.
TIP
In coding interviews, initializing two pointers with "left, right = 0, len(arr) - 1" is immediately recognized as idiomatic Python and signals strong language familiarity.

Short-circuit Evaluation

Daily Life
Interviews

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.

and returns first falsy
Returns the first falsy value it finds, or the last value if all are truthy.
or returns first truthy
Returns the first truthy value it finds, or the last value if all are falsy.
Evaluation stops early
Python skips remaining expressions once the result is determined.
1print(0 and "hello")
2print("hi" and "hello")
3print([] and "hello")
>>>Output
0
hello
[]

Returns 0, "hello", and [] respectively. and returns first falsy, or last if all truthy.

1print(0 or "hello")
2print("" or [] or {})
3print("hi" or "hello")
>>>Output
hello
{}
hi

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:

1user_input = ""
2name = user_input or "Anonymous"
3print(name)
4
5env_port = None
6port = env_port or 8080
7print(port)
>>>Output
Anonymous
8080
If the left value is falsy, the right value is used as default.
TIP
Warning: value or default fails when 0, "", or [] are valid values. Use value if value is not None else default when falsy values are meaningful.

Guard Clauses

Short-circuiting prevents errors by skipping expressions that would fail. The second expression is never evaluated if the first determines the result:
1if x != 0 and 10/x > 2:
2 process(x)
3
4if node and node.next:
5 node = node.next
6
7if i < len(arr) and arr[i] == target:
8 return True
9
10while current and current.next:
11 current = current.next
The second expression is never evaluated if the first determines the result.
Order matters in guard clauses. Always put the cheaper/safer check first:
Correct Order
  • if x and x.expensive():
  • if i < len(arr) and arr[i]:
  • if node and node.val > 0:
Will Crash
  • if x.expensive() and x:
  • if arr[i] and i < len(arr):
  • if node.val > 0 and node:
Python Quiz

> 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)
in
not
or
and

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

Daily Life
Interviews

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.

NoneFalse0, 0.0, 0j""[], (), {}
None
No value
The null or nothing type
False
Boolean false
The explicit false value
0, 0.0, 0j
Zero numerics
Zero in any numeric type
""
Empty string
A string with no content
[], (), {}
Empty boxes
Empty list, tuple, or dict
Everything else is truthy. This includes things that might surprise you:
1print(bool("False"))
2print(bool("0"))
3print(bool([0]))
4print(bool([False]))
5print(bool({0: 0}))
6print(bool(-1))
>>>Output
True
True
True
True
True
True
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:
Do
  • if items:
  • if not name:
  • while stack:
  • if node:
Don't
  • if len(items) > 0:
  • if name == "":
  • while len(stack) > 0:
  • if node != None:
Fill in the Blank

> 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")
These truthy/falsy patterns appear constantly in algorithmic code. Here is a valid parentheses checker using stack truthiness:
1def valid_parentheses(s):
2 stack = []
3 pairs = {')': '(', ']': '[', '}': '{'}
4 for char in s:
5 if char in '([{':
6 stack.append(char)
7 elif char in ')]}':
8 if not stack or stack.pop() != pairs[char]:
9 return False
10 return not stack
Tree inorder traversal:
1def inorder(root):
2 result, stack, current = [], [], root
3 while current or stack:
4 while current:
5 stack.append(current)
6 current = current.left
7 current = stack.pop()
8 result.append(current.val)
9 current = current.right
10 return result

None vs Falsy

When you need to distinguish None from other falsy values (0, "", []), use is None or is not None:

1def binary_search(arr, target):
2 left, right = 0, len(arr) - 1
3 while left <= right:
4 mid = (left + right) // 2
5 if arr[mid] == target:
6 return mid
7 elif arr[mid] < target:
8 left = mid + 1
9 else:
10 right = mid - 1
11 return None
Problem: 0 is a valid return value but falsy. Wrong check:
1result = binary_search(arr, target)
2if result:
3 print(f"Found at {result}")
Correct check:
1if result is not None:
2 print(f"Found at {result}")
TIP
Use is None and is not None instead of == None. The "is" operator is faster and more explicit about identity comparison.

Ternary Expressions

Daily Life
Interviews

Write conditional assignments in one line

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.
01
Write the pattern
value_if_true if condition else value_if_false
02
Read like English
Use "x" if the condition is true, else use "y".
03
Both must be values
Each branch must be an expression that produces a value, not a statement.
1n = 7
2status = "even" if n % 2 == 0 else "odd"
3print(status)
4
5x = -5
6sign = 1 if x >= 0 else -1
7print(sign)
8
9a, b = 10, 25
10max_val = a if a > b else b
11print(max_val)
>>>Output
odd
-1
25
In return statements and list comprehensions:
1def abs_value(x):
2 return x if x >= 0 else -x
3
4signs = [1 if x >= 0 else -1 for x in numbers]

Interview Applications

Ternary expressions appear constantly in algorithmic solutions for handling edge cases and making decisions inline:
1def my_max(a, b):
2 return a if a > b else b
3
4def clamp(val, lo, hi):
5 return lo if val < lo else hi if val > hi else val
6
7def safe_sum(arr):
8 return sum(arr) if arr else 0

When NOT to Use Ternary

Ternary expressions prioritize conciseness, but readability matters more. Avoid nesting and complex conditions:
Acceptable
  • x if condition else y
  • a if a > b else b
  • val if val else default
Too Complex
  • 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
Bad - nested ternary that's hard to read:
1grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
Better - use if-elif for multiple conditions:
1if score >= 90:
2 grade = "A"
3elif score >= 80:
4 grade = "B"
5elif score >= 70:
6 grade = "C"
7else:
8 grade = "F"
Fill in the Blank

> 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)
The ternary expression reads naturally once you internalize the word order: the true value comes first, then the condition, then the false value.
In competitive programming and interview settings, ternary expressions appear constantly in return statements and list comprehensions where every character of brevity counts.
TIP
Keep ternary expressions simple and flat. If you find yourself writing a nested ternary, switch to a regular if-elif chain. Readability always wins over cleverness.

Walrus Operator (:=)

Daily Life
Interviews

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.

Assign and test at once
Store a value and check it in the same expression, reducing duplication.
Filter in comprehensions
Compute a value, filter on it, and keep it, all in one pass.
Loop with assignment
Read data and loop until exhausted, without a separate read-ahead.
Without walrus - assign then test:
1data = get_data()
2if data:
3 process(data)
With walrus - assign and test simultaneously:
1if (data := get_data()):
2 process(data)

Avoiding Repeat Computation

The walrus operator shines when you need to use a computed value in both a condition and the body:
1if len(result := expensive_list()) > 10:
2 for item in result:
3 process(item)
4
5while (line := file.readline()):
6 process(line)
7
8if (match := pattern.search(text)):
9 print(f"Found: {match.group()}")

In List Comprehensions

Walrus is particularly useful in list comprehensions when both the condition and the value need a computed result:
1results = [sq for n in numbers if (sq := n**2) > 50]
2
3valid = [processed for item in items
4 if (processed := validate(item)) is not None]
Compute once, use twice in the comprehension.
Debug Challenge

> This list comprehension has a duplicated keyword that causes a syntax error. Find and remove the extra tile.

SyntaxError: invalid syntax

Interview Applications

In interviews, walrus can make solutions more concise, but use it judiciously. Clarity trumps cleverness:
1def find_pair(arr, diff):
2 seen = set()
3 for num in arr:
4 if (complement := num - diff) in seen or \
5 (complement := num + diff) in seen:
6 return (num, complement)
7 seen.add(num)
8 return None
BFS with level tracking:
1while queue:
2 level = []
3 for _ in range(n := len(queue)):
4 node = queue.pop(0)
5 level.append(node.val)
6 if node.left:
7 queue.append(node.left)
8 if node.right:
9 queue.append(node.right)
10 result.append(level)
TIP
In interviews, walrus operator can impress but can also confuse interviewers unfamiliar with it. Consider your audience and prioritize clear communication over clever syntax.

Chained Comparisons

Python allows chaining comparison operators, which reads naturally and is more efficient than using "and" to combine conditions:
1x = 5
2print(0 < x < 10)
3
4a, b, c = 1, 2, 3
5print(a < b < c)
6
7a, b, c = 5, 5, 5
8print(a == b == c)
>>>Output
True
True
True
Common interview applications:
Grid bounds checking (very common):
1def is_valid(grid, row, col):
2 return 0 <= row < len(grid) and 0 <= col < len(grid[0])
Sliding window bounds:
1for i in range(len(arr)):
2 if 0 <= i - k < i + k < len(arr):
3 process_window(arr[i-k:i+k+1])

Interview Pattern Summary

These are the syntax patterns that appear most frequently in technical interviews. Memorize them and practice until they are automatic:
01
Swap values
arr[i], arr[j] = arr[j], arr[i] for in-place element swaps.
02
Two pointers
left, right = 0, len(arr) - 1 to initialize boundary pointers.
03
Guard clauses
while node and node.next: to safely traverse linked structures.
04
Default values
result = value or default to provide fallback values.
05
Bounds checking
0 <= i < len(arr) to validate indices with chained comparisons.
06
Inline branching
return x if condition else y for concise conditional returns.
Choosing the right syntax pattern under interview pressure is a skill in itself. The scenario below simulates a real interview decision.
The Interview ProblemStep 1
>

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.

problem_info
detailvalue
array_sizeup to 10^6
time_limitO(log n)
May 2026
Algorithm Choice

The array is sorted and the expected complexity is O(log n). What approach do you use?

Keep these quick-reference rules in mind when writing Python in high-pressure situations.
INTERVIEW SYNTAX CHECKLIST
  • Initialize pointers with multiple assignment, not separate lines
  • Use chained comparisons for bounds: 0 <= i < n
  • Guard with short-circuit: if node and node.val
  • Prefer ternary for simple one-line conditionals
  • Use is None instead of == None
These patterns compound. A single function might use multiple assignment for initialization, short-circuit guards in the loop condition, and a ternary in the return value, all working together.
PUTTING IT ALL TOGETHER

> 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.

Multiple assignment unpacks event fields like user_id, event_type, ts = record in one line, eliminating separate index lookups.
Short-circuit evaluation lets config.get("limit") or 1000 supply a safe default without an explicit None check.
Truthy and falsy rules mean an empty events list or zero count is treated as falsy, so the guard fires without an explicit == 0.
The walrus operator := reads the next batch and assigns it inside the while condition, collapsing fetch-and-check into a single expression.
KEY TAKEAWAYS
a, b = b, a swaps without a temp variable (right side evaluates first)
and/or return actual values, not booleans; enable guards and defaults
Falsy: None, False, 0, "", [], {}, (). Everything else is truthy
Use is None when 0, "", [] are valid values
Ternary: x if cond else y for inline conditionals
Walrus := assigns and returns in one expression
Chained comparisons: 0 <= x < len(arr) for bounds

Python 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

  1. 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

  2. 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:

  3. 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

  4. 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 -

  5. 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