Python Junior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. Which of these built-in types is immutable?
Correct answer:
tupleTuples, strings, numbers and frozensets can't change after creation. Lists, dicts and sets can be modified in place.
2. What does this code print?
a = [1, 2, 3] b = a b.append(4) print(a)Correct answer: [1, 2, 3, 4]
Assignment doesn't copy.
aandbare two names for the same list, so appending throughbis visible througha.3. What is the difference between
==andis?Correct answer:
==compares values,ischecks that both names point to one object==calls__eq__and compares content.iscompares identity. Useisfor singletons likeNone, and==for values.4. How should you check that a variable is
None?Correct answer:
if x is None:Noneis a singleton, so PEP 8 recommendsis None.== Noneusually works but can be fooled by a custom__eq__.5. What does
7 // 2return?Correct answer: 3
//is floor division: it rounds down to the nearest integer./always returns a float, so7 / 2is 3.5.6. What does
-7 // 2return?Correct answer: -4
Floor division rounds towards negative infinity, not towards zero. -3.5 rounded down is -4.
7. What does
print(0.1 + 0.2 == 0.3)print?Correct answer: False
Floats are binary fractions, so 0.1 and 0.2 can't be stored exactly and the sum is 0.30000000000000004. Compare with
math.iscloseor usedecimal.8. Which values are falsy in Python?
Correct answer:
0,"",[],{}andNoneZero of any numeric type, empty strings and containers,
NoneandFalseare falsy. That's whyif items:is the idiomatic emptiness check.9. What does
[1, 2, 3, 4, 5][1:4]return?Correct answer: [2, 3, 4]
A slice starts at the first index and stops before the second. Index 1 is 2, and index 4 (the value 5) is excluded.
10. What does
s[::-1]do with a strings?Correct answer: Returns a reversed copy of the string
A step of -1 walks the sequence backwards. Strings are immutable, so a slice always builds a new string.
11. What happens when you run this code?
s = "hello" s[0] = "H"Correct answer: A
TypeError: strings don't support item assignmentStrings are immutable. Build a new one instead, for example
"H" + s[1:]ors.capitalize().12. What is the idiomatic way to join a list of strings with commas?
Correct answer:
",".join(items)joinis a string method: the separator is the object and the iterable is the argument. Every item must be a string.13. What does this f-string print?
price = 3.14159 print(f"{price:.2f}")Correct answer: 3.14
After the colon comes a format spec.
.2fmeans fixed-point with two digits after the decimal point.14. What is the difference between
list.append(x)andlist.extend(x)?Correct answer:
appendaddsxas one item,extendadds each item ofx[1].append([2, 3])gives[1, [2, 3]], while[1].extend([2, 3])gives[1, 2, 3].15. What does
list.sort()return?Correct answer:
None, because it sorts the list in placeMethods that change an object in place return
Noneby convention. Usesorted(items)when you need a new list.16. How do you sort a list of words by length?
Correct answer:
sorted(words, key=len)keytakes a function that is called once per item, and items are compared by its result. Addreverse=Truefor descending order.17. What is the idiomatic way to loop over a list with indexes?
Correct answer:
for i, item in enumerate(items):enumerateyields(index, item)pairs and takes an optionalstart.range(len(items))works too but reads worse.18. What does
zip([1, 2, 3], ["a", "b"])produce when turned into a list?Correct answer: [(1, 'a'), (2, 'b')]
zipstops at the shortest iterable. Passstrict=Trueto get an error on different lengths, or useitertools.zip_longestto pad.19. What does
range(2, 10, 3)produce?Correct answer: 2, 5, 8
range(start, stop, step)starts at 2, adds 3 each time and stops before 10.20. When does the
elseblock of aforloop run?Correct answer: When the loop finishes without hitting
breakfor ... elseis handy for searches:breakwhen found, andelsehandles the not-found case. It also runs for an empty iterable.21. What does this list comprehension produce?
[x * x for x in range(6) if x % 2 == 0]Correct answer: [0, 4, 16]
The filter keeps 0, 2 and 4, and each is squared. The order is: expression,
forclause, then the optionalif.22. How do you build a dict that maps each word to its length?
Correct answer:
{w: len(w) for w in words}A dict comprehension uses curly braces and
key: value. Curly braces with a single expression make a set comprehension instead.23. What does
d.get("missing")return when the key is absent?Correct answer:
None, or a default you pass as the second argumentd[key]raisesKeyError, whiled.get(key, default)returnsdefault(orNone). Use it when a missing key is a normal case.24. In what order does iterating over a dict return its keys?
Correct answer: In insertion order, guaranteed since Python 3.7
Dicts keep insertion order as part of the language spec since 3.7. Sets, however, still have no defined order.
25. Why can't a list be used as a dict key?
Correct answer: Lists are mutable and not hashable
Keys need a stable hash. A list's contents can change, so it has no
__hash__. Use a tuple instead.26. What is the fastest way to remove duplicates from a list of hashable items if order doesn't matter?
Correct answer:
list(set(items))A set keeps only unique items. If order matters,
list(dict.fromkeys(items))keeps the first occurrence of each.27. What does
{1, 2, 3} & {2, 3, 4}return?Correct answer: {2, 3}
&is intersection.|is union,-is difference and^is symmetric difference.28. How do you create an empty set?
Correct answer:
set(){}creates an empty dict for historical reasons, and()is an empty tuple. Onlyset()gives an empty set.29. How do you create a tuple with one element?
Correct answer:
(1,)The comma makes the tuple, not the parentheses.
(1)is just the number 1, andtuple(1)fails because 1 isn't iterable.30. What is the Pythonic way to swap two variables?
Correct answer:
a, b = b, aThe right side builds a tuple first, then it's unpacked into the names. No temporary variable needed.
31. What does
first, *rest = [1, 2, 3, 4]assign torest?Correct answer: [2, 3, 4]
A starred target collects the remaining items into a list. It can appear once in any position, for example
*init, last = items.32. What does this code print?
def add(item, items=[]): items.append(item) return items print(add(1)) print(add(2))Correct answer: [1], then [1, 2]
Default values are evaluated once, when the function is defined. All calls share one list. Use
items=Noneand create the list inside.33. What do
*argsand**kwargscollect in a function signature?Correct answer: Extra positional arguments into a tuple, extra keyword ones into a dict
The names are a convention, the stars matter. They are often used to pass arguments through, as in
f(*args, **kwargs).34. What does a function without a
returnstatement return?Correct answer:
NoneEvery call returns something. If the body never hits
return(or uses a barereturn), the result isNone.35. In which order does Python look up a name inside a function?
Correct answer: Local, enclosing function, global, built-in
This is the LEGB rule. The first scope that has the name wins, so a local variable can shadow a built-in like
list.36. What happens when you run this code?
count = 0 def inc(): count += 1 inc()Correct answer: An
UnboundLocalErrorAssigning to a name anywhere in a function makes it local for the whole body, so
count += 1reads a local that has no value yet.global countfixes it.37. What is
nonlocalfor?Correct answer: Rebinding a variable of the enclosing function from a nested one
Without
nonlocal, assigning inside the nested function creates a new local.globaldoes the same for module-level names.38. What is a limitation of
lambdain Python?Correct answer: Its body is a single expression, no statements
A lambda can't contain assignments, loops or
return. For anything bigger, a nameddefis clearer.39. What does
if __name__ == "__main__":do?Correct answer: Runs the block only when the file is executed directly
When run as a script, the module's
__name__is"__main__". When imported, it's the module name, so the block is skipped.40. What does
import mathdo the second time it runs in the same process?Correct answer: Takes the already loaded module from
sys.modulesModules are executed once and cached. Repeat imports just bind the cached object to a name.
41. Why is
from module import *discouraged?Correct answer: It hides where names come from and can shadow existing ones
Readers and linters can't tell which names exist, and an import can silently overwrite a local name. PEP 8 advises against it.
42. What is a virtual environment for?
Correct answer: Keeping a project's packages separate from other projects
Each venv has its own
site-packages, so two projects can use different versions of one library. Create it withpython -m venv .venv.43. Why run
python -m pip install ...instead of justpip install ...?Correct answer: It installs into exactly the Python you invoked
With several Pythons on a machine, a bare
pipmay belong to a different one.python -m pipremoves that ambiguity.44. What does PEP 8 recommend for indentation?
Correct answer: 4 spaces per level
Indentation is syntax in Python, and mixing tabs and spaces is an error in Python 3. Formatters like Ruff or Black apply 4 spaces automatically.
45. Which naming style does PEP 8 use for functions and classes?
Correct answer:
snake_casefor functions,CapWordsfor classesConstants are
UPPER_CASE, and a leading underscore marks a name as internal.46. What is
selfin a method?Correct answer: The instance the method was called on, passed in first
obj.method(x)is roughlyClass.method(obj, x).selfis only a convention, but everyone uses it.47. What does
__init__do?Correct answer: Initializes a new instance after it has been created
__new__creates the object and__init__sets it up. You almost never need to override__new__.48. What does this code print?
class Dog: tricks = [] a, b = Dog(), Dog() a.tricks.append("sit") print(b.tricks)Correct answer: ['sit']
tricksis a class attribute shared by all instances. Create per-instance lists in__init__withself.tricks = [].49. What is the difference between
__str__and__repr__?Correct answer:
__str__is for users,__repr__is an unambiguous form for developersprintandstr()use__str__, and the REPL, debuggers and containers use__repr__. If only__repr__exists,str()falls back to it.50. What does
super().__init__()do in a subclass?Correct answer: Calls the parent's
__init__so it can set up its partIf a subclass defines
__init__, the parent's version isn't called automatically.super()follows the MRO, so it also works with multiple inheritance.51. What does
isinstance(True, int)return?Correct answer: True
boolis a subclass ofint, soTrue == 1andTrue + True == 2. Keep that in mind when validating numbers.52. Why is
isinstance(x, Base)usually better thantype(x) == Base?Correct answer: It also accepts instances of subclasses
Exact type checks break when someone passes a subclass.
isinstancealso takes a tuple of types.53. What does "duck typing" mean in Python?
Correct answer: Code relies on the methods an object has, not on its class
"If it walks like a duck and quacks like a duck": a function that calls
.read()works with any file-like object.54. What does the
elseblock oftrydo?Correct answer: Runs only if the
tryblock raised no exceptionCode in
elseisn't protected by theexceptclauses, so errors there aren't caught by mistake.finallyruns in every case.55. When does the
finallyblock run?Correct answer: Always, whether an exception happened or not
It runs even after
returnorbreakintry. It's the place for cleanup like closing a connection.56. Why is a bare
except:a bad idea?Correct answer: It also catches
KeyboardInterruptandSystemExitA bare
exceptcatches everyBaseException, so Ctrl+C orsys.exit()can be swallowed. Catch the specific exceptions you expect.57. How do you raise an error when a function gets an invalid argument?
Correct answer:
raise ValueError("age must be positive")raisetakes an exception instance.ValueErrorfits a value of the right type that is out of range,TypeErrorfits the wrong type.58. Which exception does
[1, 2, 3][5]raise?Correct answer:
IndexErrorSequences raise
IndexErrorfor an index out of range, and mappings raiseKeyErrorfor a missing key. Both inherit fromLookupError.59. Why open files with
with open(...) as f:?Correct answer: The file is closed even if an error happens
withcalls the context manager's exit method on leaving the block. Without it, an exception may leave the file open.60. What should you pass to
open()when reading a text file to avoid platform-dependent surprises?Correct answer:
encoding="utf-8"Without
encoding, Python has historically used the locale's encoding, which differs on Windows. Binary mode returns bytes, not text.61. Which module gives an object-oriented way to work with file paths?
Correct answer:
pathlibPath("data") / "users.json"builds paths portably, and methods like.read_text()and.exists()replace manyos.pathcalls.62. What does
json.loadsdo?Correct answer: Parses a JSON string into Python objects
loadsanddumpswork with strings,loadanddumpwith file objects. JSON objects become dicts and arrays become lists.63. What does
print(2 ** 100)print?Correct answer: 1267650600228229401496703205376
Python integers have arbitrary precision, so they don't overflow. Only floats are limited to 64 bits.
64. What does
round(2.5)return?Correct answer: 2
rounduses banker's rounding: halves go to the nearest even number, soround(2.5)is 2 andround(3.5)is 4.65. What does
1 < x < 10mean in Python?Correct answer:
1 < x and x < 10Comparisons chain, and
xis evaluated only once. That's whya == b == calso works as expected.66. What does
"" or "default"evaluate to?Correct answer: "default"
orreturns the first truthy operand or the last one, not a bool. Be careful: it also replaces valid falsy values like 0.67. What is Python's conditional expression syntax?
Correct answer:
a if condition else bThe condition sits in the middle. Keep it short; nested conditional expressions are hard to read.
68. What does
grid = [[0] * 3] * 3create?Correct answer: Three references to the same inner list
Changing
grid[0][0]changes every row. Build independent rows with[[0] * 3 for _ in range(3)].69. What does
copy.copy(nested_list)copy?Correct answer: The outer list only; inner lists are still shared
A shallow copy creates a new container with the same items. Use
copy.deepcopyto copy nested objects too.70. What is the average time complexity of
x in some_set?Correct answer: O(1)
Sets and dicts are hash tables.
x in some_list, by contrast, scans the list and is O(n).71. What is
passused for?Correct answer: As a placeholder where a statement is required
An empty block is a syntax error, so
passfills it.continueskips to the next iteration, andreturnexits a function.72. What does a docstring do?
Correct answer: Documents code and is available as
__doc__The first string literal in a body becomes its docstring.
help()and IDEs show it. PEP 257 describes the conventions.73. What does
matchdo in Python 3.10 and later?Correct answer: Compares a value against structural patterns
Structural pattern matching can destructure sequences, dicts and objects.
case _:is the catch-all.74. How does pytest know that a function is a test?
Correct answer: Its name starts with
testin atest_*.pyfilepytest discovers tests by naming conventions and uses plain
assertstatements, rewriting them to show detailed failure messages.75. How do you check in pytest that code raises an exception?
Correct answer:
with pytest.raises(ValueError):The test fails if the block doesn't raise. Add
match="..."to check the message as well.