Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Interview questions › Python

Python interview questions

1. What are the key features of Python?

Easy

Interpreted, dynamically typed, high-level and garbage collected. It supports procedural, object-oriented and functional styles, has a huge standard library ("batteries included") and very readable syntax based on indentation.

2. List vs tuple?

Easy

List is mutable ([1, 2], can append/remove), tuple is immutable ((1, 2)). Tuples are slightly faster, can be dictionary keys (if their items are hashable) and signal "this data should not change".

3. What are the built-in data types in Python?

Easy

Numbers: int, float, complex, bool. Sequences: str, list, tuple, range. Mapping: dict. Sets: set, frozenset. Plus bytes, bytearray and NoneType.

4. Mutable vs immutable objects?

Easy

Mutable objects can be changed in place: list, dict, set, user classes. Immutable ones cannot: int, float, str, tuple, frozenset. "Changing" an immutable creates a new object.

s = "hi"; s += "!"   # a new string, s now points to it

5. What is the difference between `is` and `==`?

Easy

== compares values (calls __eq__), is compares identity (same object in memory). Use is only for singletons like None: if x is None.

6. How is memory managed in Python?

Medium

CPython uses a private heap. Objects are freed by reference counting as soon as nothing points to them; a cyclic garbage collector (module gc) cleans up reference cycles. Small ints and some strings are cached (interned).

7. What are *args and **kwargs?

Easy

*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict.

def f(a, *args, **kwargs):
    print(a, args, kwargs)
f(1, 2, 3, x=4)   # 1 (2, 3) {'x': 4}

8. What is a list comprehension?

Easy

A compact way to build a list from an iterable, optionally with a condition.

squares = [x * x for x in range(10) if x % 2 == 0]

There are also dict ({k: v for ...}), set ({x for ...}) and generator ((x for ...)) comprehensions.

9. What is a lambda function?

Easy

An anonymous one-expression function: lambda x, y: x + y. Handy as a short key or callback, e.g. sorted(people, key=lambda p: p.age). For anything longer, use def.

10. What are decorators?

Medium

A decorator is a function that takes a function and returns a new one, adding behaviour around it. @timer above def f means f = timer(f).

def timer(fn):
    def wrap(*a, **k):
        import time; t = time.time()
        r = fn(*a, **k)
        print(time.time() - t)
        return r
    return wrap

11. What are generators and `yield`?

Medium

A function with yield returns a generator: it produces values one at a time and pauses between them, keeping its state. It saves memory for large or infinite sequences.

def count_up(n):
    i = 0
    while i < n:
        yield i
        i += 1

12. Iterator vs iterable?

Medium

An iterable can give an iterator (list, str, dict) — it has __iter__. An iterator returns the next value with __next__ and raises StopIteration at the end. for calls iter() then next() repeatedly.

13. Shallow copy vs deep copy?

Medium

copy.copy(x) (or list(x), x[:]) copies the outer object but shares the inner objects. copy.deepcopy(x) copies everything recursively, so nested lists/dicts are independent.

14. How do you handle exceptions in Python?

Easy

With try / except / else / finally.

try:
    n = int(s)
except ValueError as e:
    print("not a number", e)
else:
    print("ok")
finally:
    print("always runs")

Raise your own with raise ValueError("msg").

15. What is the GIL?

Hard

The Global Interpreter Lock in CPython lets only one thread run Python bytecode at a time. Threads still help for I/O-bound work (network, files) but not for CPU-bound work — use multiprocessing or native extensions for that.

16. Multithreading vs multiprocessing in Python?

Hard

Threads share memory and are limited by the GIL — good for I/O-bound tasks. Processes have separate memory and run truly in parallel on multiple cores — good for CPU-bound tasks, but communicating between them costs more.

17. What does `if __name__ == "__main__":` do?

Easy

__name__ is "__main__" only when the file is run directly. Code under this check runs when you execute the script but not when another file imports it — useful for tests and demos.

18. What is `self`?

Easy

self is the instance a method is called on. Python passes it automatically as the first argument: obj.method(x) becomes Class.method(obj, x). The name is a convention, not a keyword.

19. What is `__init__`?

Easy

The initializer called after a new object is created, used to set its attributes. It is not the constructor itself — __new__ creates the object, __init__ sets it up.

20. Class method vs static method vs instance method?

Medium

Instance methods get self. @classmethod gets the class (cls) — often used as alternative constructors. @staticmethod gets neither — a plain function grouped inside the class.

21. Does Python support multiple inheritance? What is MRO?

Medium

Yes. The Method Resolution Order decides which parent's method is used, computed with C3 linearisation. See it with ClassName.__mro__. super() follows the MRO.

22. What are dunder (magic) methods?

Easy

Special methods with double underscores that Python calls for operators and built-ins: __init__, __str__, __repr__, __len__, __eq__, __add__, __getitem__, __iter__. Defining them makes your class behave like built-in types.

23. `__str__` vs `__repr__`?

Easy

__str__ is the readable form for users (print, str()). __repr__ is the unambiguous form for developers (shell, repr()), ideally valid code to recreate the object. If __str__ is missing, __repr__ is used.

24. How do you make an attribute private in Python?

Medium

There are no truly private attributes. _name means "internal, please don't touch" by convention. __name triggers name mangling (_ClassName__name) to avoid clashes in subclasses. Use @property for controlled access.

25. What is a property?

Medium

@property turns a method into a read-only attribute; add @x.setter for validation on assignment.

class Temp:
    def __init__(self): self._c = 0
    @property
    def c(self): return self._c
    @c.setter
    def c(self, v):
        if v < -273: raise ValueError
        self._c = v

26. What are Python namespaces and the LEGB rule?

Medium

Names are looked up in this order: Local → Enclosing function → Global (module) → Built-in. Use global x to assign a module variable inside a function and nonlocal x for an enclosing function's variable.

27. What is a mutable default argument trap?

Medium

Default values are evaluated once, when the function is defined, so a mutable default is shared across calls.

def add(x, items=[]):   # bug: same list every call
    items.append(x); return items
# fix
def add(x, items=None):
    items = [] if items is None else items

28. How does a Python dictionary work internally?

Hard

It is a hash table: the key's hash picks a slot, and collisions are resolved by probing. Average O(1) get/set/delete. Keys must be hashable (immutable). Since Python 3.7, dicts keep insertion order.

29. set vs list — when to use which?

Easy

Use a set for fast membership tests (O(1) average) and removing duplicates; it is unordered. Use a list when order matters or you need duplicates and indexing.

30. How do you reverse a string or list?

Easy

s[::-1] returns a reversed copy (works for strings, lists, tuples). lst.reverse() reverses a list in place. reversed(x) returns an iterator.

31. What does `enumerate` and `zip` do?

Easy

enumerate(it, start=0) gives (index, value) pairs. zip(a, b) pairs items from several iterables and stops at the shortest.

for i, (name, mark) in enumerate(zip(names, marks), 1):
    print(i, name, mark)

32. What are `map`, `filter` and `reduce`?

Easy

map(f, it) applies f to each item; filter(f, it) keeps items where f is true; functools.reduce(f, it) folds the items into one value. List comprehensions are usually clearer than map/filter.

33. How do you read and write files safely?

Easy

Use a with block so the file is closed even on errors.

with open("data.txt", encoding="utf-8") as f:
    for line in f:
        print(line.strip())
with open("out.txt", "w") as f:
    f.write("hello\n")

34. What is a context manager?

Medium

An object with __enter__ and __exit__ used in a with statement to set up and always clean up a resource (files, locks, DB connections). contextlib.contextmanager builds one from a generator.

35. What are modules and packages?

Easy

A module is one .py file. A package is a folder of modules (usually with __init__.py). Import with import pkg.mod or from pkg import mod. pip installs third-party packages from PyPI.

36. What is a virtual environment?

Easy

An isolated folder with its own Python and packages, so each project keeps its own versions. python -m venv .venv, then activate it and pip install -r requirements.txt.

37. What is PEP 8?

Easy

The official style guide for Python code: 4-space indentation, snake_case for functions and variables, PascalCase for classes, lines around 79–99 characters, spaces around operators. Tools like black and flake8 enforce it.

38. How is Python compiled or interpreted?

Medium

CPython compiles source code to bytecode (.pyc files in __pycache__), which the Python virtual machine then interprets. PyPy adds a JIT compiler for speed.

39. What is duck typing?

Easy

"If it walks like a duck and quacks like a duck, it's a duck." Python cares whether an object has the needed methods, not its exact type — any object with __iter__ can be looped over, for example.

40. How do you sort a list of dictionaries by a key?

Easy

students.sort(key=lambda s: s["marks"], reverse=True)   # in place
ranked = sorted(students, key=lambda s: (-s["marks"], s["name"]))

sorted returns a new list; Python's sort (Timsort) is stable and O(n log n).

41. What is slicing?

Easy

seq[start:stop:step] returns a new sequence from start up to (not including) stop. Negative indexes count from the end: a[-1] is the last item, a[-3:] the last three, a[::2] every second item.

42. What are `any` and `all`?

Easy

any(it) is True if at least one item is truthy; all(it) is True if every item is truthy (and for an empty iterable). Example: all(x > 0 for x in nums).

43. What is the difference between `append` and `extend`?

Easy

a.append(x) adds x as one item. a.extend(it) adds each item of it.

a = [1]; a.append([2, 3])   # [1, [2, 3]]
b = [1]; b.extend([2, 3])   # [1, 2, 3]

44. How do you remove duplicates from a list but keep the order?

Easy

list(dict.fromkeys(items)) — dict keys are unique and keep insertion order. list(set(items)) also removes duplicates but loses the order.

45. What is `collections` used for?

Easy

Extra containers: Counter (count items), defaultdict (default value for missing keys), deque (fast append/pop at both ends — use it as a queue), OrderedDict, namedtuple.

from collections import Counter
Counter("banana").most_common(1)   # [('a', 3)]

46. What are type hints?

Easy

Optional annotations like def add(a: int, b: int) -> int:. Python does not enforce them at runtime, but editors and tools like mypy use them to catch bugs and improve autocomplete.

47. What are `async` and `await`?

Hard

async def defines a coroutine; await pauses it until another coroutine (like a network call) finishes, letting the event loop run other tasks meanwhile. Run with asyncio.run(main()). Best for many concurrent I/O tasks.

48. How do you swap two variables in Python?

Easy

a, b = b, a — the right side builds a tuple first, then unpacks it into the names, so no temporary variable is needed.

49. What is pickling and unpickling?

Medium

Pickling turns a Python object into a byte stream (pickle.dumps(obj) / pickle.dump(obj, file)), and unpickling rebuilds it (pickle.loads). Useful for saving objects or models to disk. Never unpickle data from an untrusted source — it can run arbitrary code. For data exchange, prefer JSON.

50. Find the most frequent element in a list.

Medium

from collections import Counter
def most_frequent(items):
    return Counter(items).most_common(1)[0][0]

O(n) time. Without imports: count with a dict, then max(counts, key=counts.get).

More topics