You ever look at a few lines of code and think, "There has to be a cleaner way to write this"? That’s exactly how I felt the first time I saw this:
temp = a
a = b
b = temp
It’s basic. It works. But… it’s not Pythonic.
🥷 Enter the Ninja Move: Multiple Assignment & Swapping
In Python, we can swap variables like this:
a, b = b, a
Boom. No temp variables, no extra lines — just clean, readable code.
It’s not just for swapping either. You can unpack multiple values in a single line:
x, y, z = 1, 2, 3
Or pull values from a list/tuple:
point = (10, 20)
x, y = point
Why This is Cool
✨ Elegant: No need for temp variables.
⚡ Efficient: Python handles the packing/unpacking for you.
📖 Readable: Easier to understand, especially when returning multiple values.
Real-world use case:
def get_bounds(values):
return min(values), max(values)
low, high = get_bounds([3, 7, 1, 9])
Just make sure the number of variables matches the number of values — or Python will remind you, quickly. 😅
🧠 More Pythonic Power: enumerate()
& Anonymous Functions
Want to level up your for
loops too? I recently wrote about the moment I discovered enumerate()
— a game-changer when looping with indices:
📖 The Day I Discovered enumerate()
in Python
It's packed with tips on anonymous functions (lambda
) too.
💪 Bonus Post: The Magic of *args
and **kwargs
Ever had a function that needs to handle some arguments now and maybe more later? Instead of rewriting it over and over, Python’s *args
and **kwargs
let you flex like a pro.
Let’s take a basic example:
def greet(*names):
for name in names:
print(f"Hello, {name}!")
greet("Alice", "Bob", "Charlie")
Or when you want keyword arguments too:
def display_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
display_info(name="Bhuvanesh", age=18, role="Developer")
Why *args
and **kwargs
Rock
✨ Flexible: Accept any number of positional or keyword arguments.
🚀 Scalable: Perfect for decorators, APIs, logging, and more.
🧩 Reusable: Write once, use in many places.
Quick Tip:
You can combine them in one function:
def log_event(event_type, *args, **kwargs):
print(f"[{event_type}]", args, kwargs)
Just keep *args
before **kwargs
in your function signature.
💬 Got your own Python ninja tricks?
Drop them in the comments — let's share the Python love 🐍
📖 For more tips and tricks in Python, check out
Packed with hidden gems, Python's underrated features and modules are real game-changers when it comes to writing clean and efficient code.
#python #cleanCode #devto #beginners #oneliners #enumerate #pythontips #tupleunpacking #lambda #args #kwargs #flexiblefunctions #coding