Python Interview Questions and Answers: 50 Python 3 Questions Grouped by Topic

Explore a comprehensive collection of Python interview questions and answers. From fundamental concepts to advanced topics, this curated list covers a wide range of Python programming topics, helping you prepare for your Python job interview.

Aug 28, 2023 - 03:45
Updated: 10 days ago
105.5k
Python Interview Questions and Answers: 50 Python 3 Questions Grouped by Topic

Quick answer: Python interviews mostly test Python 3 fundamentals: data types, lists versus tuples, dictionaries, functions, decorators, generators, object-oriented programming, exceptions and small coding tasks. This guide gives 50 questions with short answers, grouped by topic. Practise running each example yourself; interviewers prefer explanation over memorised lines.

Key takeaways

  • Everything here is Python 3; Python 2 reached end-of-life and should not be used.
  • Learn the reason behind each answer, such as why a list is mutable and a tuple is not.
  • Expect to write short code live, so practise without an autocomplete crutch.
  • Know the standard library basics: collections, itertools, json, os and pathlib.
  • Be honest about what you have not used; explain how you would find out.

Basics and data types

1. What is Python and why is it popular?

Python is a high-level, interpreted, dynamically typed language with readable syntax. It is popular because of its large standard library, ecosystem for data, web and automation work, and gentle learning curve.

2. What are the built-in data types?

Numeric types (int, float, complex), str, bool, list, tuple, set, frozenset, dict, bytes and NoneType.

3. What is the difference between mutable and immutable types?

Mutable objects such as lists, dicts and sets can change in place. Immutable objects such as int, str and tuple cannot; operations create new objects.

4. What is the difference between a list and a tuple?

Lists are mutable and tuples are immutable. Tuples can be dictionary keys when their items are hashable, and are suited to fixed records.

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

== compares values and is compares object identity. Use is mainly for None checks.

6. What is None?

None is the single object of NoneType, used to signal no value. Functions with no return statement return None.

7. How does Python manage memory?

CPython uses reference counting plus a cyclic garbage collector. Objects are freed when no references remain or when cycles are detected.

8. What are f-strings?

Formatted string literals such as f"Hello {name}". They evaluate expressions inline and are the preferred formatting style in Python 3.

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

A shallow copy duplicates the outer container but shares nested objects. A deep copy, from copy.deepcopy, duplicates nested objects as well.

10. What is PEP 8?

The official style guide for Python code, covering naming, indentation and line length. Following it keeps code consistent across a team.

Lists, dictionaries and sets

11. How do you remove duplicates from a list while keeping order?

Use list(dict.fromkeys(items)). Plain set(items) removes duplicates but does not guarantee the original order.

12. What is a list comprehension?

A compact way to build a list, for example [x*x for x in range(5) if x % 2 == 0]. It is usually faster and clearer than a manual loop.

13. How do dictionaries work?

They are hash tables mapping hashable keys to values with average constant-time lookup. Since Python 3.7, dictionaries preserve insertion order.

14. What is the difference between dict.get() and d[key]?

d[key] raises KeyError if the key is missing, while d.get(key, default) returns a default instead.

15. What is a set and when would you use it?

An unordered collection of unique hashable items. Use it for membership tests, removing duplicates and set operations such as union and intersection.

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

sorted(rows, key=lambda r: r["age"]). Add reverse=True for descending order. Sorting is stable.

17. What is the difference between sort() and sorted()?

list.sort() sorts in place and returns None. sorted() returns a new list from any iterable.

18. What does collections.Counter do?

It counts hashable items, for example Counter("banana"), and offers helpers such as most_common().

Functions and scope

19. What are *args and **kwargs?

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

20. What is a lambda function?

A small anonymous function limited to a single expression, often used as a key function. Use a normal def for anything longer.

21. What is the LEGB rule?

Name lookup order: Local, Enclosing, Global, Built-in. The global and nonlocal keywords change which scope a name binds to.

22. Why is a mutable default argument dangerous?

Defaults are evaluated once, so def f(x, items=[]) shares one list across calls. Use None as the default and create the list inside.

23. What is a closure?

A function that remembers variables from its enclosing scope after that scope has finished. Closures underpin decorators.

24. What is a decorator?

A callable that takes a function and returns a modified one, applied with @name. Common uses are logging, timing, caching and access checks.

25. What is the difference between a generator and a list?

A generator produces values lazily using yield, so it uses little memory for large or infinite sequences. A list stores all items at once.

26. What are iterators and iterables?

An iterable can return an iterator through __iter__. An iterator implements __next__ and raises StopIteration when finished.

Object-oriented programming

27. What are the four pillars of OOP in Python?

Encapsulation, inheritance, polymorphism and abstraction. Python supports them through classes, method overriding, duck typing and abstract base classes.

28. What is the difference between a class method, a static method and an instance method?

Instance methods take self, class methods take cls via @classmethod, and static methods take neither via @staticmethod.

29. What is __init__?

The initialiser called after an object is created, used to set up instance attributes. The constructor proper is __new__.

30. What is method resolution order?

The order Python searches classes for a method, computed with C3 linearisation. Inspect it with ClassName.__mro__.

31. What are dunder methods?

Special methods such as __str__, __repr__, __len__ and __eq__ that let objects work with built-in operations.

32. What is a dataclass?

A decorator from the dataclasses module that generates __init__, __repr__ and comparison methods from annotated fields.

33. What is duck typing?

Behaviour matters more than declared type: if an object has the needed methods, it can be used, whatever its class.

Errors, files and modules

34. How does exception handling work?

Use try, except, else and finally. Catch specific exceptions, not bare except:, and let unexpected errors surface.

35. What does the with statement do?

It uses a context manager to guarantee set-up and clean-up, for example closing a file even if an error occurs.

36. How do you read a file safely?

with open("data.txt", encoding="utf-8") as f: then iterate over lines. Always state the encoding.

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

A module is a single.py file. A package is a directory of modules, usually with an __init__.py file.

38. What is a virtual environment?

An isolated Python environment with its own packages, created with python -m venv, so projects do not clash on dependency versions.

39. What does if __name__ == "__main__" do?

It runs code only when the file is executed directly, not when it is imported as a module.

Advanced topics

40. What is the GIL?

The Global Interpreter Lock in CPython lets only one thread run Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work. Recent Python releases include experimental free-threaded builds, so check current documentation.

41. What is asyncio?

A library for single-threaded concurrency using async def and await, suited to many network or file waits.

42. What are type hints?

Optional annotations such as def add(a: int, b: int) -> int. They are not enforced at run time but help editors and tools such as mypy.

43. What is the difference between multithreading and multiprocessing?

Threads share memory in one process and are limited by the GIL for CPU work. Processes have separate memory and run truly in parallel.

44. What is monkey patching?

Changing a class or module at run time. It is useful in tests but risky in production code.

45. What are __slots__?

A class attribute that fixes the allowed instance attributes, reducing memory use and preventing accidental new attributes.

Coding round warm-ups

46. How do you reverse a string?

s[::-1] is the shortest form. Be ready to explain slicing and to write a loop version too.

47. How do you check whether a string is a palindrome?

Normalise case and characters, then compare with the reversed string: t == t[::-1].

48. How do you find the most frequent word in text?

Split the text, count with Counter and use most_common(1). Mention how you handle punctuation and case.

49. How do you swap two variables?

a, b = b, a. Python evaluates the right side first, so no temporary variable is needed.

50. How do you generate Fibonacci numbers efficiently?

Use a generator with two variables, updating them in a loop, instead of naive recursion that repeats work. Memoisation with functools.lru_cache is another valid answer.

How to prepare

  • Run every example above in a terminal and change it to see the result.
  • Solve a few array, string and dictionary problems daily on a practice platform.
  • Keep one project you can explain end to end, including your design choices.
  • Learn the basics of Git, testing with pytest and reading tracebacks.

Common mistakes

  • Memorising answers without running code.
  • Using Python 2 syntax such as the print statement or xrange.
  • Catching all exceptions silently.
  • Not asking clarifying questions in a coding round.

Next steps

Practise with the Python programming course. For more questions, read common Python interview questions, Python coding interview questions and Python technical interview questions.

Related reading

Frequently Asked Questions

Data types, lists and dictionaries, functions, decorators, generators, object-oriented programming, exception handling, file handling, modules and common libraries are asked most often. Coding rounds add strings, arrays and dictionary problems.

A list is mutable and a tuple is immutable. Lists suit collections that change, while tuples suit fixed records and can be dictionary keys when their contents are hashable. Tuples are slightly lighter in memory.

A decorator is a function that takes another function and returns a modified version, applied with the at symbol. It is used for logging, timing, caching and permission checks without changing the original function body.

Revise fundamentals, then solve small problems daily on strings, lists and dictionaries, writing code without autocomplete. Learn to explain time complexity, handle edge cases and talk through your approach aloud while you code.

No. Python 2 reached end-of-life and interviews expect Python 3. If you see old syntax such as the print statement or xrange in study material, replace it with Python 3 equivalents like print() and range().

No. A smaller set of core questions that you truly understand and can run in code beats a long list you memorise. Cover the fundamentals above, then add topics from the job description.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Wow Wow 0
Sad Sad 0
Angry Angry 0
Aayushi Sinha

With a passion for staying on the cutting edge of technology trends, I am dedicated to delivering content that not only informs but also inspires. Whether you need in-depth analysis pieces, informative guides, or thought-provoking opinion pieces, I craft content that resonates with tech enthusiasts and professionals alike.