Python / Core Python Fundamentals Interview Questions
What is the walrus operator (:=) and when is it useful?
The walrus operator (:=), introduced in Python 3.8 (PEP 572), is the assignment expression operator. It assigns a value to a variable as part of a larger expression rather than as a standalone statement. The name comes from its resemblance to a walrus face with tusks.
# Without walrus — evaluate twice
data = fetch_data()
if data:
process(data)
# With walrus — evaluate once, assign, and test in one expression
if data := fetch_data():
process(data)
# Classic use: while loop reading chunks from a file
with open('large.bin', 'rb') as f:
while chunk := f.read(8192):
process_chunk(chunk)
# Filtering with a computed value — avoid calling the function twice
results = [cleaned for raw in records
if (cleaned := clean(raw)) is not None]The walrus operator is most valuable when you need to compute a value, test it, and use it — and calling the computation twice would be wasteful or have side effects. Common patterns: while loops reading from streams, filtering list comprehensions where the filter function is expensive, and reducing nested if-statements.
Avoid overusing it — plain assignment on a separate line is often more readable. The walrus is idiomatic in tight loops and comprehensions; in most other code the conventional two-step (assign then test) is clearer.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
