🧠 Insight: Test Your Python Skills With These Brain Teasers 🐍
🧠 Insight: Test Your Python Skills With These Brain Teasers 🐍
This article was originally published on Medium.
Think you know Python? These seven gotchas will test your instincts, twist your brain, and make you question everything — just a little.
Python is beloved for being elegant, readable, and… completely unpredictable if you’re not paying attention. If you think you know Python inside and out, these brain teasers might just leave you scratching your head — or flipping a table.
Let’s play a game. Below are a few seemingly innocent Python snippets. You guess what happens. Answers and explanations follow, but no peeking. Unless you’re one of those people.
1️⃣ What gets printed?
def func(a, b=[]):
b.append(a)
return b
print(func(1))
print(func(2))
print(func(3))
You think:
Every call to func
should return a new list, right? Right??
Actual Output:
[1]
[1, 2]
[1, 2, 3]
Why:
Default mutable arguments are shared between calls. Python’s way of saying, “You sure you know what you’re doing, buddy?”
2️⃣ What does this print?
x = 10
def foo():
print(x)
foo()
Output:
10
Now try this:
x = 10
def bar():
print(x)
x = 5
bar()
Output:
UnboundLocalError: cannot access local variable 'x'
where it is not associated with a value
Why:
Python sees x = 5
and says, “Aha! A local variable!” Then it yells at you for referencing it before assigning. Very helpful. Very rude.
3️⃣ What’s this return?
print('' or [] or {} or 0 or 'finally')
Answer:
finally
Why:
The or
operator returns the first truthy value. And 'finally'
finally breaks the chain of sadness.
4️⃣ What’s the type?
a = (1)
print(type(a))
Answer:
<class 'int'>
Why:
Parentheses alone don’t make a tuple. You need a trailing comma, like (1,)
, or else Python says, "Nice try.”
5️⃣ Which line throws?
try:
raise Exception("uh oh")
except Exception as e:
raise e
finally:
raise Exception("but wait")
Answer:
The finally
block wins. Always. Even over another exception.
Output:
Exception: but wait
Why:
It’s like Python saw your chaos and said, “Hold my beer.”
6️⃣ What gets printed?
word = "banana"
print(word[::-1][0])
Answer:
a
Why:
First it reverses the string: “ananab”. Then grabs the first character: “a”. Two slicing tricks for the price of one. Python loves its little surprises.
7️⃣ What does this do?
def printer(*args, **kwargs):
print("args:", args)
print("kwargs:", kwargs)
printer(1, 2, 3, a=4, b=5)
Output:
args: (1, 2, 3)
kwargs: {'a': 4, 'b': 5}
Why:
The *args
gobbles up positional arguments. The **kwargs
devours keyword ones. It's the Hungry Hungry Hippos of function parameters.
So What Did We Learn?
Python’s got quirks. But that’s half the fun.
If you enjoyed these, let me know — there are plenty more where they came from. Or go ahead and flex on your teammates at your next code review. Just be nice about it.
Want a part two? I’ve got enough Python puzzles to last us through the next LTS release.
🔍 Where These Teasers Show Up in Real Life
Think these are just trivia-night tricks? Think again. Here’s where each of these sneak attacks might show up in your daily Python grind:
- Default mutable arguments — This bites devs writing helper functions, especially in class methods or utility libraries. It’s a classic source of bugs.
- UnboundLocalError from assignments — Super common in functions trying to use or modify globals. Seen in everything from scripts to Django views.
or
truthiness chains — You’ll spot this in config loaders, data fallbacks, and web app defaults. Pythonistas love chainingor
like it’s going out of style.- Tuple vs int confusion — Shows up in return statements, unpacking logic, or when zipping and expecting tuples. A tiny typo, a big headache.
finally
overridingraise
— Rare but wild. Most often appears in custom error handlers, test teardown code, or badly writtentry/except
blocks.- Slicing and indexing tricks — These are everyday tools in string wrangling, list reversals, and interview questions that make you look brilliant.
*args
and**kwargs
— Essential for decorators, wrappers, CLI tools, and any framework that does dynamic argument passing. These aren’t just cute. They’re core.
Written for the brilliant minds over at “Python in Plain English.” You know who you are.
Aaron Rose is a software engineer and technology writer.
Comments
Post a Comment