InterviewQs

🐍 Python Programming Interview Questions

Top 28 Questions & Answers

Top Python Interview Questions

1. What is Python?

Python is a high-level, interpreted programming language known for its readability and simplicity. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming.

2. What are Python's key features?

Python's key features include: Readable and maintainable code, Dynamic typing, Interpreted language, Extensive standard libraries, Supports multiple programming paradigms, and Cross-platform compatibility.

3. What are Python's built-in data types?

int, float, complex, str, list, tuple, dict, set.

4. What is a Python function?

A block of reusable code defined using the def keyword. It can take arguments and return values.

5. What are Python modules and packages?

Modules are Python files; packages are collections of modules. They help in organizing and reusing code.

6. What is a list comprehension?

A concise way to create lists using a single line with loops and conditionals.

7. How does Python handle memory management?

Python uses automatic memory management with garbage collection and reference counting.

8. What is exception handling in Python?

Using try and except blocks to manage runtime errors without crashing.

9. What is the difference between deepcopy and shallow copy?

Shallow copy references objects; deepcopy copies everything recursively.

10. What are decorators in Python?

Functions that modify other functions using the @decorator_name syntax.

11. Difference between == and is?

== checks value equality, is checks object identity.

12. What is a lambda function?

An anonymous function defined using lambda for short operations.

13. Difference between a list and a tuple?

Lists are mutable; tuples are immutable.

14. What are iterators and generators?

Iterators implement __iter__() and __next__(); generators use yield.

15. How does Python handle multiple inheritance?

Using the C3 linearization algorithm to resolve method order.

16. What are context managers?

Objects used with the with statement to manage resources, using __enter__ and __exit__.

17. Purpose of self in Python?

Refers to the instance inside class methods.

18. What is the GIL?

Global Interpreter Lock prevents multiple threads from running Python bytecode simultaneously.

19. Python's built-in functions?

Examples: print(), len(), type(), sum(), max(), min().

20. What is list slicing?

Extracting parts of a list using start:stop:step syntax.

21. Method vs function?

Method is bound to an object; function is independent.

22. Purpose of __init__ method?

Initializes a new object’s attributes when it's created.

23. Handling missing keys in dictionaries?

Use get() or collections.defaultdict for default values.

24. What are decorators and how do they work?

Decorators modify behavior of functions using the @ syntax.

25. Purpose of __str__ method?

Defines human-readable string representation of an object.

26. Python’s data structures?

List, Tuple, Dictionary, Set.

27. File I/O in Python?

Use open(), read(), write(), and close() methods with modes like 'r', 'w', 'a'.

28. What is PEP 8?

PEP 8 is the style guide for writing clean and readable Python code.

29. What are Python docstrings?

Docstrings are special strings used to document functions, classes, and modules. They're written using triple quotes and can be accessed using the __doc__ attribute.

30. What is a virtual environment in Python?

A virtual environment is an isolated Python environment used to manage project-specific dependencies without affecting global Python installations.

31. What is the difference between Python 2 and Python 3?

Python 3 is the future and supports modern features like Unicode by default, new syntax (e.g., print() as a function), and better standard libraries. Python 2 reached end-of-life in 2020.

32. What is the purpose of pass in Python?

pass is a null operation used as a placeholder where syntactically required but no action is needed (e.g., empty loops or function bodies).

33. What is the use of assert in Python?

assert is used for debugging and testing by verifying that a condition is True. If not, it raises an AssertionError.

34. How is memory managed in Python?

Python manages memory using reference counting and a cyclic garbage collector for unused memory cleanup.

35. What is monkey patching in Python?

Monkey patching is dynamically changing a class or module at runtime, often for testing or hotfixing behavior.

36. What is the difference between __str__ and __repr__?

__str__ is for user-friendly string output; __repr__ is for unambiguous representation mainly used for debugging.

37. What are *args and **kwargs in Python?

*args collects variable positional arguments, and **kwargs collects variable keyword arguments.

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

Mutable types (e.g., list, dict) can be changed after creation. Immutable types (e.g., int, str, tuple) cannot be modified after creation.

39. What are Python’s control flow statements?

They include if, else, elif, for, while, break, continue, and pass.

40. What is list unpacking?

List unpacking assigns values from a list or tuple directly to variables using a comma-separated syntax.

41. What is slicing and how is it used in strings?

Slicing extracts substrings using string[start:end] or [::step]. It supports negative indices too.

42. What is the difference between append() and extend() in lists?

append() adds one element to the list; extend() adds all elements from an iterable.

43. What are Python comprehension types?

List, Set, Dict comprehensions: compact syntax for generating collections from iterables.

44. What is the difference between pop() and remove()?

pop() removes and returns an item by index. remove() deletes the first occurrence by value.

45. What is a frozenset?

An immutable version of a Python set — cannot be changed after creation.

46. What are metaclasses in Python?

Metaclasses define the behavior of classes themselves — like a class of a class.

47. What is method overloading in Python?

Python doesn't support traditional method overloading, but you can use default arguments or *args to simulate it.

48. What is duck typing?

A concept where type checking is based on behavior (methods/attributes), not the actual object type.

49. What are Python magic methods?

Special methods with double underscores (e.g., __init__, __str__, __len__) that enable operator overloading and customization.

50. How do you handle circular imports in Python?

Avoid them using local imports or restructuring modules to break the dependency loop.

Responsive Footer | Tailwind CSS