Python Trending

Python Interview Questions: Top 50 with Answers

Fifty conceptual Python interview questions with short, precise answers, grouped by topic: basics, types and mutability, data structures, functions and scope, OOP, iterators and decorators, errors and files, and internals, with runnable examples for the ones people most often get wrong.

GloryTecks Team

Training & Placement Faculty

8 June 2026 10 min read

Last updated: 24 September 2026

Share:

Python interviews test two things: whether you can write working code, and whether you understand what the language is doing when it runs. This page covers the second: fifty conceptual questions, each with the answer an interviewer is hoping for, stated briefly and precisely. Where a short example makes the point faster than prose, it is included and runs as shown. For coding tasks in plain Python, such as counting, grouping, joining and parsing, see Python interview questions for data roles.

Language basics

1. What kind of language is Python?

A high-level, dynamically typed, garbage-collected language. The standard implementation, CPython, compiles source code to bytecode and runs it on a virtual machine; "interpreted" is shorthand for that.

2. What does dynamically typed mean?

Types belong to objects, not to variable names. A name can refer to an integer and later to a string; type errors are found when the operation runs. Type hints document intent and let external checkers find mistakes, but the interpreter does not enforce them.

3. What is PEP 8?

The style guide for Python code: naming conventions, layout and programming recommendations. Teams usually enforce it with a formatter and a linter.

4. What is the difference between a module and a package?

A module is a single .py file. A package is a directory of modules, normally with an __init__.py, imported with dotted names such as package.module.

5. What does if name equals main do?

if __name__ == "__main__": runs a block only when the file is executed directly, not when it is imported, so a module can be both importable and runnable.

6. What is the difference between is and ==?

== compares values; is compares identity, whether two names refer to the same object. Use is only for singletons such as None.

python
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b, a is b, a is c)
text
True False True

7. What values are falsy?

None, False, zero of any numeric type, and empty containers: "", [], (), {}, set() and range(0) (Python docs: truth value testing). Everything else is truthy unless its class defines __bool__ or __len__ otherwise.

Types and mutability

8. Which built-in types are mutable?

Lists, dictionaries, sets and bytearrays. Immutable: integers, floats, strings, tuples, frozensets and bytes (Python docs: data model).

9. Why does mutability matter?

Because names refer to objects. Two names referring to one list see each other's changes, and a mutable object shared across calls or instances changes for everyone who holds it.

10. Is Python pass-by-value or pass-by-reference?

Neither label fits; the Python FAQ calls it pass by assignment. The function receives a reference to the same object. Mutating that object is visible to the caller; rebinding the parameter name is not (Python programming FAQ).

python
def modify(items, label):
    items.append(4)       # mutates the caller's list
    label = "changed"     # rebinds a local name only

nums, name = [1, 2, 3], "original"
modify(nums, name)
print(nums, name)
text
[1, 2, 3, 4] original

11. Why is a mutable default argument a bug?

Default values are evaluated once, when the function is defined, so every call shares the same list or dictionary. Use None as the default and create the object inside the function.

12. Can a tuple change?

The tuple itself cannot, but if it contains a mutable object, such as a list, that object can change. Such a tuple is not hashable and cannot be a dictionary key.

13. What does hashable mean?

An object has a hash value that never changes during its lifetime and can be compared for equality. Only hashable objects can be dictionary keys or set members, which is why lists cannot and tuples of immutable values can.

14. What is the difference between a shallow and a deep copy?

A shallow copy creates a new container holding the same inner objects; a deep copy recursively copies the inner objects too. copy.copy and slicing are shallow; copy.deepcopy is deep.

Data structures

15. List or tuple?

A list for a variable-length collection of similar items that may change; a tuple for a fixed record, as a dictionary key, or to signal that the data should not change. Lists vs tuples vs sets vs dictionaries goes deeper.

16. How are dictionaries implemented, and are they ordered?

As hash tables, giving average constant-time lookup, insertion and deletion. Since Python 3.7, dictionaries preserve insertion order as a language guarantee.

17. When would you use a set?

For membership tests and removing duplicates, both average constant time, and for set algebra: union, intersection and difference.

18. What does the collections module add?

Specialised containers: deque for fast appends and pops at both ends, Counter for counting, defaultdict for grouping, namedtuple for lightweight records. See the Python data structures reference.

19. What is the cost of x in a list compared with a set?

O(n) for a list, which checks element by element, and O(1) on average for a set, which hashes the value.

20. How do you sort by several keys?

Pass a key function returning a tuple, such as sorted(people, key=lambda p: (p.city, -p.age)). Python's sort is stable, so sorting in several passes, least important key first, also works.

21. What is a list comprehension, and when should you avoid one?

A compact expression that builds a list from an iterable with an optional filter. Avoid it for side effects, deeply nested loops or logic that needs statements such as try.

Functions and scope

22. What are args and kwargs?

In a definition, *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary. In a call, * and ** unpack sequences and dictionaries into arguments.

23. What is the LEGB rule?

Name lookup order: Local, Enclosing function, Global (module), Built-in (Python tutorial: scopes and namespaces).

24. What do global and nonlocal do?

They let a function assign to a name in the module scope or in an enclosing function's scope. Without them, assignment creates a local variable.

python
def counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

tick = counter()
print(tick(), tick(), tick())
text
1 2 3

25. What is a closure?

A nested function that remembers variables from the scope where it was created, even after that scope has finished, like increment above holding on to count.

26. Why do lambdas created in a loop all return the same value?

Closures look up variables when called, not when created, so they all see the loop variable's final value. Bind the value with a default argument, as in lambda x, n=n: x * n.

python
funcs = [lambda: n for n in range(3)]
fixed = [lambda n=n: n for n in range(3)]
print([f() for f in funcs], [f() for f in fixed])
text
[2, 2, 2] [0, 1, 2]

27. What is a lambda?

An anonymous function limited to a single expression, most useful as a short key or callback argument.

28. What are first-class functions?

Functions are objects: they can be assigned to variables, stored in containers, passed as arguments and returned from other functions. Decorators and callbacks depend on this.

29. What do positional-only and keyword-only parameters mean?

Parameters before / can only be passed by position; parameters after * can only be passed by keyword. Both make call sites clearer and APIs easier to change.

Object-oriented Python

30. What is self?

The instance a method is called on. Python passes it automatically as the first argument, so obj.method() is Class.method(obj).

31. What is the difference between a class attribute and an instance attribute?

A class attribute is shared by all instances; an instance attribute is set on self and belongs to one object. A mutable class attribute shared by accident is a classic bug.

32. What are classmethod and staticmethod?

A classmethod receives the class and is typically used for alternative constructors. A staticmethod receives neither the class nor the instance; it is a plain function grouped inside the class.

33. What is the MRO?

The method resolution order: the order Python searches classes for an attribute under inheritance, computed with the C3 linearisation. super() follows it.

python
class Base: pass
class Left(Base): pass
class Right(Base): pass
class Child(Left, Right): pass
print([c.__name__ for c in Child.__mro__])
text
['Child', 'Left', 'Right', 'Base', 'object']

34. What are dunder methods?

Special methods such as __init__, __repr__, __eq__, __len__ and __iter__ that let objects work with Python's syntax and built-in functions.

35. What does a dataclass generate?

@dataclass writes __init__, __repr__ and __eq__ from the annotated fields; options add ordering, immutability (frozen=True) or __slots__.

36. How does Python handle private attributes?

By convention. A leading underscore marks a name as internal; two leading underscores trigger name mangling, which prevents accidental clashes in subclasses but not deliberate access. The OOP guide shows these in a worked example.

Iterators, generators and decorators

37. What is the difference between an iterable and an iterator?

An iterable can produce an iterator through iter(). An iterator produces values with next() and raises StopIteration at the end; it can be consumed only once.

38. What is a generator?

A function containing yield. Calling it returns an iterator that runs the body lazily, pausing at each yield with its local state preserved. See Python generators and iterators.

39. What is the difference between a generator expression and a list comprehension?

Round brackets produce a lazy generator; square brackets build the whole list in memory at once.

40. What is a decorator?

A function that takes a function and returns a replacement, applied with @. @decorator above a definition is shorthand for func = decorator(func).

41. Why use functools.wraps?

It copies the wrapped function's name, docstring and other metadata onto the wrapper, so debugging, logging and documentation tools see the real function.

42. What is a context manager?

An object with __enter__ and __exit__ used in a with block, guaranteeing clean-up however the block ends. contextlib.contextmanager builds one from a generator.

Errors and files

43. What do else and finally do in a try statement?

else runs only if the try block raised nothing; finally always runs, for clean-up.

44. What does raise from do?

It chains exceptions: the new exception's __cause__ is set to the original, and the traceback shows both. It is how you translate a low-level error into a domain error without losing information.

45. Why should you always pass an encoding to open()?

Without one, Python uses the platform's locale encoding, which differs between systems, so the same file can be read differently on Windows and Linux.

46. What is the difference between except Exception and a bare except?

A bare except: also catches KeyboardInterrupt and SystemExit, which break Ctrl+C and deliberate exits. Catch specific exceptions, or Exception at most.

Performance and internals

47. What is the GIL?

The global interpreter lock in CPython, which lets only one thread execute Python bytecode at a time (Python glossary: GIL). Threads help with I/O-bound work; processes are needed for CPU-bound Python code.

48. How does Python manage memory?

Mainly by reference counting: an object is freed when its count reaches zero. A cyclic garbage collector finds groups of objects that refer to each other and are otherwise unreachable (Python docs: gc).

49. Threads, processes or asyncio?

Threads or asyncio for waiting on I/O, processes for CPU-bound Python work. Multithreading vs multiprocessing shows the difference with timings.

50. How do you find out why code is slow?

Measure before changing anything: timeit for small snippets, cProfile for whole programs. Then fix the algorithm or data structure, such as a set instead of a list, before reaching for parallelism.

How to use this list

Do not memorise the answers. For each question, say the answer aloud in two or three sentences, then write a five-line example that demonstrates it. Interviewers follow up on anything you mention, so an answer you can illustrate is worth more than one you can recite. The concepts here map onto the modules of the Python Programming course, from data structures and functions to object-oriented programming, advanced concepts and exception handling.

Sources

GloryTecks Team

Training & Placement Faculty

The GloryTecks faculty team mentors learners across Data Science, AI and Data Engineering, with a focus on real-time projects and placement readiness in Hyderabad.

Want to master Python?

Join GloryTecks’ expert-led Python Programming training in Hyderabad with real-time projects and 100% placement support.

Explore course