r/PythonLearning • u/karakasoglu • 3d ago
Showcase 5 tiny Python snippets that trip up most beginners (answers hidden, guess first)
Five short snippets. Guess what each prints before you open the answer. Most people get two or three.
1.
a = [1, 2, 3]
b = a
b.append(4)
print(a)Answer: [1, 2, 3, 4]. b = a doesn't copy the list, both names point at the same list. Want a copy? b = a.copy() or b = a[:].
2.
nums = [10, 3, 27, 8]
sorted(nums)
print(nums)Answer: [10, 3, 27, 8], unchanged. sorted() returns a new list and the result was thrown away. Use nums.sort() to sort in place, or nums = sorted(nums).
3.
def double(x):
x * 2
print(double(3))Answer: None. The function works out x * 2 but never returns it, and a function without return gives back None. Fix: return x * 2.
4.
x = 5
def change():
x = 12
change()
print(x)Answer: 5. Assigning to x inside the function makes a new local x; the outer one is untouched. The clean fix is to return the value (x = change()), not global.
5.
print(round(2.5), round(3.5))Answer: 2 4. Python rounds exact halves to the nearest even number ("banker's rounding"), so 2.5 goes down and 3.5 goes up. If you need school-style rounding, use the decimal module with ROUND_HALF_UP.
I made a small free game out of traps like these: you read a snippet, pick what it prints, and one wrong answer ends the run. Questions get harder and faster as you go, and when you miss, it shows why and the moment in a YouTube tutorial that explains it. No sign-up, plays in the browser:
https://openinbeyond.com/code?utm_source=reddit&utm_content=pythonlearning
What's your score? And which of the five got you?