🦦 Python Hack: The Walrus Operator `:=`

 

🦦 Python Hack: The Walrus Operator `:=`





Meet the walrus. It assigns and returns a value in one go. Streamlined, cheeky, low-key underrated. 🦦✨


👶 Starter move: instead of doing this ⬇️

data = input("Enter something: ")
if len(data) > 5:
    print("Too long!")

Do this ⬇️

if (n := len(data := input("Enter something: "))) > 5:
    print(f"{n} chars? bruh that’s long 😅")

⚡ Cleaner loops:

# old way
lines = []
while True:
    text = input("Line (blank to quit): ")
    if not text:
        break
    lines.append(text)

# walrus way
lines = []
while (text := input("Line (blank to quit): ")):
    lines.append(text)

Less noise, more flow. 🎶


📊 Inline checks:

numbers = [1, 7, 42, 99, 420]

if (big := max(numbers)) > 100:
    print(f"Biggest flex: {big} 🤯")
else:
    print(f"All chill. Max is {big}.")

💀 Beast Mode Combo: compact list building + condition in one line

# get words > 3 chars, keep their lengths
words = ["hi", "walrus", "op", "legend", "goat"]
lengths = [n for w in words if (n := len(w)) > 3]

print(lengths)  # 👉 [6, 6, 4]

One liner. Assign, filter, and keep results in the same breath. That’s walrus energy. 🦦💪


Aaron Rose is a software engineer and technology writer at tech-reader.blog and the author of Think Like a Genius.

Comments

Popular posts from this blog

The New ChatGPT Reason Feature: What It Is and Why You Should Use It

Raspberry Pi Connect vs. RealVNC: A Comprehensive Comparison

Running AI Models on Raspberry Pi 5 (8GB RAM): What Works and What Doesn't