Interview Questions
Tricky Python Output Questions · Study material
Tricky Python – Interview Questions
1. Why does a list default argument keep growing between calls?
Defaults are evaluated once when def runs, so every call without that argument shares the same list. Use None and create the list inside.
2. Why does [lambda: i for i in range(3)] give functions that all return 2?
Late binding: each lambda looks up i when called, after the loop has finished. Capture with lambda i=i: i.
3. What is the difference between a = a + [x] and a += [x] for lists?
+ creates a new list and rebinds a; += extends the existing list in place, so every alias sees the change.
4. Why does round(2.5) return 2?
Python rounds halves to the nearest even number (banker's rounding).
5. Why is -7 // 2 equal to -4?
// is floor division, which rounds toward minus infinity.
6. Why is [] == False False when [] is falsy?
Truthiness (bool([])) and equality are different questions; a list never equals a bool.
7. What does print(nums.sort()) print?
None – sort() sorts in place and returns None.
8. Why is {1: "a", True: "b"} a one-key dictionary?
1 == True and hash(1) == hash(True), so they are the same key.
9. Why does a second sum() over a generator return 0?
The first sum exhausted the generator; it cannot be restarted.
10. Does finally run if try returns?
Yes; finally runs before the function returns to its caller.
11. Why can changing one object change "another" object?
Both names refer to the same object (aliasing) – common with lists, dicts and class attributes.
12. Why does x = 10 inside a function not change a global x?
Assignment creates a local variable unless the name is declared global (or nonlocal).
13. What is printed by print(print("a"))?
"a" on one line, then None – the inner print returns None.
14. Why is 0.1 + 0.2 == 0.3 False?
Binary floating point cannot represent these decimals exactly; the sum is 0.30000000000000004.
15. Why does modifying a list while looping over it skip items?
Removing an item shifts the later items left, while the loop's internal index moves on.