Python interview questions for beginners
AdvertisementPython interviews for beginners test two things: whether you know the core ideas, and whether you can predict what a few lines of code do. The questions below are the ones asked most often, with short answers and examples that were actually run (Python 3.9; results are the same in newer versions). Use them to find gaps, then fix the gaps by writing code. The free Python video course covers every topic here, and the Python cheat sheet is a quick reference.
Basics
1. What is Python, and what are its main features?
A high-level, interpreted, dynamically typed, general-purpose language with readable syntax, automatic memory management and a large standard library. It supports procedural, object-oriented and functional styles.
2. Is Python compiled or interpreted?
Both, in a sense. Python source is compiled to bytecode, which the Python virtual machine then interprets. You do not run a separate compile step.
3. What does "dynamically typed" mean?
Variables have no declared type; the value has the type, and a name can be rebound to a value of another type. Python is also strongly typed: it will not silently mix unrelated types ("1" + 1 raises TypeError).
4. What are Python's built-in data types?
Numbers (int, float, complex), bool, str, list, tuple, dict, set, frozenset, bytes and NoneType.
5. What is the difference between /, // and %?
/ true division (always a float), // floor division, % remainder.
print(7/2, 7//2, 7%2, -7//2, divmod(17,5))
# 3.5 3 1 -4 (3, 2)
Note -7//2 is -4: floor division rounds toward negative infinity.
Mutability and copies
6. What is the difference between a list and a tuple?
Lists are mutable and written with []; tuples are immutable and written with (). Tuples are used for fixed records and can be dictionary keys or set members (if their items are hashable). A one-item tuple needs a comma: (1,), because (1) is just the integer 1.
7. What is mutable and what is immutable?
Mutable objects can be changed in place (list, dict, set). Immutable ones cannot (int, float, str, tuple, frozenset, bytes); operations create a new object.
8. What does b = a do for a list?
It copies nothing: both names refer to the same list.
a = [1, 2]; b = a; c = a[:]
b.append(3)
print(a, c, a is b, a is c, a == c)
# [1, 2, 3] [1, 2] True False False
9. What is the difference between a shallow and a deep copy?
A shallow copy (copy.copy, list[:]) creates a new outer container but shares the inner objects. A deep copy (copy.deepcopy) copies everything.
import copy
n = [[1], [2]]
sh, dp = copy.copy(n), copy.deepcopy(n)
n[0].append(9)
print(sh, dp)
# [[1, 9], [2]] [[1], [2]]
10. What is the difference between == and is?
== compares values; is compares identity (same object in memory). Use is for None (if x is None), not for numbers or strings.
11. What are truthy and falsy values?
Falsy: False, None, 0, 0.0, "", [], (), {}, set(). Everything else is truthy, including "0" and [0].
print(bool([]), bool(""), bool(0), bool(None), bool("0"), bool([0]))
# False False False False True True
Strings, lists and dictionaries
12. How does slicing work?
seq[start:stop:step]; stop is excluded and negative indexes count from the end.
s = "Hello, World"
print(s[0], s[-1], s[7:], s[::-1])
# H d World dlroW ,olleH
13. What is the difference between sort() and sorted()?
list.sort() sorts in place and returns None. sorted(x) returns a new sorted list from any iterable and leaves the original alone. Both accept key= and reverse=.
14. How do you remove duplicates from a list and keep the order?
list(dict.fromkeys(items)), because dictionaries keep insertion order and keys are unique. list(set(items)) also removes duplicates but loses the order.
15. dict[key] or dict.get(key)?
d["k"] raises KeyError if missing; d.get("k") returns None (or a default you give): d.get("z", 0).
16. What is a list comprehension?
A compact way to build a list: [x*x for x in range(5) if x % 2 == 0] gives [0, 4, 16]. Dictionary and set comprehensions work the same way with {}.
Functions and scope
17. What are *args and **kwargs?
*args collects extra positional arguments into a tuple, **kwargs collects extra keyword arguments into a dict.
def f(a, b=2, *args, **kw):
return a, b, args, kw
print(f(1, 3, 4, 5, x=9))
# (1, 3, (4, 5), {'x': 9})
18. What is the mutable default argument problem?
Default values are evaluated once, when the function is defined, so a mutable default is shared between calls.
def bad(x, acc=[]):
acc.append(x); return acc
print(bad(1)); print(bad(2))
# [1]
# [1, 2] <- surprising: the same list is reused
Fix: use None as the default and create the list inside the function.
19. Explain variable scope (LEGB).
Python looks up a name in this order: Local, Enclosing function, Global, Built-in. Assigning to a name inside a function makes it local unless you declare global or nonlocal.
20. What is a closure?
A function that remembers variables from the enclosing scope after that function has returned.
def counter():
c = 0
def inc():
nonlocal c
c += 1
return c
return inc
i = counter()
print(i(), i())
# 1 2
21. What is a lambda?
A small anonymous function limited to one expression: sorted(people, key=lambda p: p["age"]). Use a normal def when it needs more than that.
22. What is a generator?
A function that uses yield to produce values lazily, one at a time, keeping its state between calls. It uses little memory, which suits large or endless sequences.
def gen(n):
for i in range(n):
yield i * i
print(list(gen(4)), sum(gen(4)))
# [0, 1, 4, 9] 14
Object-oriented Python
23. What are self, __init__ and __repr__?
self is the instance a method works on. __init__ initialises a new object. __repr__ returns an unambiguous string for developers (shown by print of a list of objects and in the shell); __str__ is the friendly version.
24. What is the difference between instance, class and static methods?
An instance method receives self. A @classmethod receives the class (cls) and is often used as an alternative constructor. A @staticmethod receives neither; it is a plain function placed in the class for organisation.
class P:
count = 0
def __init__(self, n): self.n = n; P.count += 1
@classmethod
def make(cls, n): return cls(n)
@staticmethod
def hi(): return "hi"
p = P("a"); q = P.make("b")
print(P.count, P.hi())
# 2 hi
25. How does inheritance work?
A subclass takes the attributes and methods of its parent and can override them. Call the parent with super(). isinstance(obj, Class) checks the type including parents, and issubclass checks classes. Python supports multiple inheritance, resolved by the method resolution order (Class.__mro__).
26. What is a decorator?
A function that takes a function and returns a modified one, applied with @name. @property, @classmethod and @functools.lru_cache are examples. lru_cache makes a recursive Fibonacci fast: fib(30) returns 832040 instantly.
Errors, files and modules
27. How does exception handling work?
try runs the code, except handles a named error, else runs if there was no error, and finally always runs.
try:
int("x")
except ValueError as e:
print("ValueError:", e)
else:
print("no error")
finally:
print("done")
# ValueError: invalid literal for int() with base 10: 'x'
# done
Catch specific exceptions; a bare except: hides bugs. Common ones: ValueError, TypeError, KeyError, IndexError, ZeroDivisionError, FileNotFoundError.
28. Why use with open(...)?
The with statement guarantees the file is closed, even if an error occurs, because the file object is a context manager.
29. What does if __name__ == "__main__": do?
It runs the block only when the file is executed directly, not when it is imported as a module, so a file can be both a script and a library.
30. Why does 0.1 + 0.2 == 0.3 give False?
Floats are stored in binary and many decimals cannot be represented exactly.
print(0.1 + 0.2, 0.1 + 0.2 == 0.3)
# 0.30000000000000004 False
Compare with a tolerance (math.isclose) or use decimal.Decimal for money.
Coding tasks to practise
Interviewers often follow the questions with a small task. Practise these until you can write them from memory:
- Reverse a string without a loop (
s[::-1]). - Count how often each word appears (
collections.Counter). - Check whether a word is a palindrome.
- Find the second largest number in a list.
- Flatten a list of lists with a comprehension.
- Write a function that returns the first non-repeating character.
- Read a file and print its longest line.
Write each one, run it, then try to break it with an empty input, a single item and a repeated value.
Advice for the interview
- Explain your thinking as you write code.
- Name edge cases (empty list,
None, negative numbers). - Know the standard library basics:
collections,itertools,json,re,datetime. - Admit what you do not know and describe how you would find out.
Test your regular expressions with the Regex Tester and your JSON with the JSON Formatter while you practise. If you are learning from scratch, the guide to the Python video course shows how to work through it.