Loading lesson...
Patterns for technical interviews
Patterns for technical interviews
Topics covered: Multiple Assignment, Short-circuit Evaluation, Truthy and Falsy Values, Ternary Expressions, Walrus Operator (:=)
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
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:
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
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 -
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