Python Fundamentals Interview Questions
Comprehensive python fundamentals interview questions and answers for Python. Prepare for your next job interview with expert guidance.
Questions Overview
1. What is Python and what are its primary characteristics?
Basic2. Explain the difference between Python 2 and Python 3.
Moderate3. What is the Global Interpreter Lock (GIL) in Python?
Advanced4. What are the main programming paradigms supported by Python?
Basic5. How does Python's memory management work?
Moderate6. Explain the concept of duck typing in Python.
Advanced7. What is the difference between .py and .pyc files?
Basic8. What are decorators in Python?
Moderate9. Describe Python's method resolution order (MRO).
Advanced10. What is PEP 8 and why is it important?
Basic11. Explain the difference between lists and tuples in Python.
Basic12. What are lambda functions in Python?
Moderate13. How does Python's 'with' statement work?
Moderate14. What is the difference between deep and shallow copy?
Advanced15. Explain Python's namespaces and scoping rules.
Advanced16. What are generator functions in Python?
Moderate17. What is the purpose of the __init__ method in Python classes?
Basic18. How does Python handle multiple inheritance?
Advanced19. What are context managers in Python?
Moderate20. Explain the difference between == and is operators in Python.
Basic21. What are metaclasses in Python?
Advanced22. How do you handle exceptions in Python?
Basic23. What is the purpose of the __str__ and __repr__ methods?
Moderate24. Explain Python's garbage collection mechanism.
Advanced25. What are magic methods (dunder methods) in Python?
Moderate26. How does Python support functional programming?
Moderate27. What is the difference between abstract base classes and interfaces in Python?
Advanced28. Explain type hinting and its benefits in Python.
Moderate29. What are *args and **kwargs in Python functions?
Basic30. How does Python implement data encapsulation?
Moderate31. What is the difference between lists and tuples in Python?
Basic32. Explain the difference between '==' and 'is' operators in Python.
Basic33. What are the different numeric data types in Python?
Basic34. How does Python handle variable scoping?
Moderate35. What is list comprehension and what are its advantages?
Moderate36. Explain slicing in Python and its extended form.
Basic37. What are Python's string formatting methods?
Moderate38. How does Python's garbage collection work?
Advanced39. What are the different types of operators in Python?
Basic40. How do you handle type hints in Python?
Moderate41. What are generator expressions and when should they be used?
Advanced42. Explain the difference between deep and shallow copy.
Moderate43. What are magic methods (dunder methods) in Python?
Advanced44. How does Python handle memory management?
Advanced45. What are the different ways to handle conditional execution?
Basic46. How do you use walrus operator (:=) and what are its benefits?
Advanced47. What are the different loop control statements in Python?
Basic48. How does Python handle variable assignment and reference?
Moderate49. What are sequence unpacking and packing in Python?
Moderate50. How do you handle string encoding and decoding in Python?
Advanced51. What are the differences between range, xrange (Python 2), and range (Python 3)?
Moderate52. How do you handle boolean operations and short-circuit evaluation?
Basic53. What are f-strings and their advanced features?
Moderate54. How does Python handle integer division and floating-point arithmetic?
Moderate55. What are the different ways to comment Python code?
Basic56. How do you use match statements (pattern matching) in Python?
Advanced57. What are the naming conventions in Python?
Basic58. How does Python handle operator precedence?
Moderate59. What are the different number systems and their representation in Python?
Moderate1. What is Python and what are its primary characteristics?
BasicPython is a high-level, interpreted programming language created by Guido van Rossum. It is known for its simplicity, readability, and versatility, with key characteristics including dynamic typing, automatic memory management, and support for multiple programming paradigms.
2. Explain the difference between Python 2 and Python 3.
ModeratePython 3 is a major revision of the language that is not fully backward-compatible with Python 2. Key differences include print function vs. print statement, integer division behavior, Unicode string handling, and removal of certain legacy syntax.
3. What is the Global Interpreter Lock (GIL) in Python?
AdvancedThe Global Interpreter Lock is a mutex that prevents multiple native threads from executing Python bytecodes simultaneously. It's a mechanism in CPython that ensures thread safety but can limit the performance of multi-threaded programs, especially in CPU-bound tasks.
4. What are the main programming paradigms supported by Python?
BasicPython supports multiple programming paradigms, including object-oriented programming (OOP), functional programming, and procedural programming. It allows developers to use different programming styles based on their requirements.
5. How does Python's memory management work?
ModeratePython uses automatic memory management with reference counting and garbage collection. Objects are created dynamically, and memory is automatically allocated and freed. The reference count of an object is incremented when it's assigned to a variable and decremented when references are removed.
6. Explain the concept of duck typing in Python.
AdvancedDuck typing is a dynamic typing concept in Python where the type or class of an object is less important than the methods it defines. If an object has all the methods and properties required for a particular use, it can be used, regardless of its actual type.
7. What is the difference between .py and .pyc files?
Basic.py files are source code files containing Python script, while .pyc files are compiled bytecode files that are created to improve performance by reducing compilation time in subsequent runs.
8. What are decorators in Python?
ModerateDecorators are a design pattern in Python that allows modifying or enhancing functions or classes without directly changing their source code. They are functions that take another function as an argument and return a modified version of that function.
9. Describe Python's method resolution order (MRO).
AdvancedMethod Resolution Order (MRO) is the order in which Python looks for methods in a hierarchy of classes. It uses the C3 linearization algorithm to determine the order of method resolution in multiple inheritance scenarios, ensuring a consistent and predictable method lookup.
10. What is PEP 8 and why is it important?
BasicPEP 8 is the style guide for Python code that provides conventions for writing readable and consistent Python code. It covers aspects like indentation, naming conventions, maximum line length, and other coding standards to improve code readability and maintainability.
11. Explain the difference between lists and tuples in Python.
BasicLists are mutable, ordered collections that can be modified after creation, while tuples are immutable and cannot be changed once created. Lists use square brackets [], tuples use parentheses (), and tuples are generally more memory-efficient and can be used as dictionary keys.
12. What are lambda functions in Python?
ModerateLambda functions are small, anonymous functions defined using the 'lambda' keyword. They can have any number of arguments but can only have one expression. They are often used for short, one-time use functions, especially as arguments to higher-order functions.
13. How does Python's 'with' statement work?
ModerateThe 'with' statement is used for resource management, ensuring that a resource is properly acquired and released. It simplifies exception handling by automatically calling close() or exit() methods, making code cleaner and reducing the risk of resource leaks.
14. What is the difference between deep and shallow copy?
AdvancedA shallow copy creates a new object but references the same memory addresses for nested objects, while a deep copy creates a completely independent copy of an object and all its nested objects. The copy module provides methods for both types of copying.
15. Explain Python's namespaces and scoping rules.
AdvancedPython uses namespaces to organize and manage variable names. It follows the LEGB rule (Local, Enclosing, Global, Built-in) for variable scope resolution. Each namespace is a mapping from names to objects, and Python searches for names in this specific order.
16. What are generator functions in Python?
ModerateGenerator functions use the 'yield' keyword to return a generator iterator. They allow you to generate values on-the-fly and pause the function's state, making them memory-efficient for handling large datasets or infinite sequences.
17. What is the purpose of the __init__ method in Python classes?
BasicThe __init__ method is a special constructor method in Python classes that is automatically called when a new object is created. It initializes the object's attributes and can take parameters to set up the initial state of the object.
18. How does Python handle multiple inheritance?
AdvancedPython supports multiple inheritance, allowing a class to inherit from multiple parent classes. It uses the Method Resolution Order (MRO) to determine the order of method inheritance, resolving potential conflicts using the C3 linearization algorithm.
19. What are context managers in Python?
ModerateContext managers are objects that define __enter__ and __exit__ methods, used with the 'with' statement to manage resources. They provide a clean way to set up and tear down resources, ensuring proper initialization and cleanup.
20. Explain the difference between == and is operators in Python.
BasicThe '==' operator checks for value equality, comparing the values of two objects, while the 'is' operator checks for identity, verifying if two references point to the exact same object in memory.
21. What are metaclasses in Python?
AdvancedMetaclasses are classes of classes, allowing you to customize class creation. They define how a class behaves and can modify the class definition at runtime. The type class is the default metaclass in Python.
22. How do you handle exceptions in Python?
BasicPython uses try-except blocks to handle exceptions. You can catch specific exceptions, use multiple except blocks, include an else clause for code to run if no exception occurs, and use a finally clause for cleanup code that always runs.
23. What is the purpose of the __str__ and __repr__ methods?
Moderate__str__ provides a human-readable string representation of an object, typically used by print(), while __repr__ returns a more detailed, unambiguous representation often used for debugging and development.
24. Explain Python's garbage collection mechanism.
AdvancedPython uses reference counting and generational garbage collection. When an object's reference count drops to zero, it's immediately deallocated. For circular references, a cyclic garbage collector periodically runs to identify and remove unreachable objects.
25. What are magic methods (dunder methods) in Python?
ModerateMagic methods, identified by double underscores (e.g., __init__, __str__), allow customization of object behavior. They define how objects interact with built-in functions and operators, enabling operator overloading and custom object implementations.
26. How does Python support functional programming?
ModeratePython supports functional programming through features like lambda functions, map(), filter(), reduce(), comprehensions, and first-class functions. These allow for writing code in a more declarative and concise manner.
27. What is the difference between abstract base classes and interfaces in Python?
AdvancedAbstract base classes (defined using the abc module) can have both abstract and concrete methods, while Python doesn't have traditional interfaces. Abstract base classes provide a way to define a blueprint for other classes, ensuring certain methods are implemented.
28. Explain type hinting and its benefits in Python.
ModerateType hinting allows specifying expected types for function parameters and return values. Introduced in Python 3.5, it improves code readability, helps catch type-related errors early, and enables better IDE support and static type checking.
29. What are *args and **kwargs in Python functions?
Basic*args allows a function to accept any number of positional arguments, while **kwargs allows accepting any number of keyword arguments. They provide flexibility in function definitions and are commonly used in wrapper functions and class inheritance.
30. How does Python implement data encapsulation?
ModeratePython uses naming conventions for encapsulation. Single underscore prefix (e.g., _variable) suggests internal use, double underscore prefix (e.g., __variable) triggers name mangling to prevent naming conflicts in inheritance.
31. What is the difference between lists and tuples in Python?
BasicLists are mutable (can be modified after creation) and use square brackets [], while tuples are immutable (cannot be modified after creation) and use parentheses (). Lists have methods like append(), remove(), while tuples have limited methods due to immutability.
32. Explain the difference between '==' and 'is' operators in Python.
Basic'==' compares the values of objects (equality), while 'is' compares the identity (memory location) of objects. For example, a == b checks if a and b have the same value, while a is b checks if they are the same object in memory.
33. What are the different numeric data types in Python?
BasicPython has int (integer), float (floating-point), complex (complex numbers) as numeric types. Integers have unlimited precision, floats are typically double-precision, and complex numbers have real and imaginary parts.
34. How does Python handle variable scoping?
ModeratePython uses LEGB rule: Local, Enclosing, Global, Built-in. Variables are first searched in local scope, then enclosing functions, then global scope, and finally built-in scope. Use 'global' keyword to modify global variables from local scope.
35. What is list comprehension and what are its advantages?
ModerateList comprehension is a concise way to create lists based on existing lists/iterables. Syntax: [expression for item in iterable if condition]. Advantages include more readable and compact code, better performance than equivalent for loops, and clearer intent.
36. Explain slicing in Python and its extended form.
BasicSlicing extracts parts of sequences using syntax sequence[start:stop:step]. Start is inclusive, stop is exclusive. Negative indices count from end. Extended form allows step value to control direction and skipping. Default step is 1.
37. What are Python's string formatting methods?
ModeratePython offers multiple string formatting methods: %-formatting (old style), str.format() method, and f-strings (3.6+). F-strings are most readable: f'{variable}'. Format() uses {}, %-formatting uses %d, %s etc. Each has different use cases and syntax.
38. How does Python's garbage collection work?
AdvancedPython uses reference counting for garbage collection, plus a cyclic garbage collector for circular references. When an object's reference count reaches zero, it's deallocated. The cyclic collector identifies and collects unreachable reference cycles periodically.
39. What are the different types of operators in Python?
BasicPython includes arithmetic (+, -, *, /, //, %, **), comparison (==, !=, >, <, >=, <=), logical (and, or, not), bitwise (&, |, ^, ~, <<, >>), assignment (=, +=, -=, etc.), and identity/membership (is, is not, in, not in) operators.
40. How do you handle type hints in Python?
ModerateType hints are added using annotations: function parameters (param: type), return types (-> type), and variable annotations (var: type). Use typing module for complex types. They're hints only, not enforced at runtime by default.
41. What are generator expressions and when should they be used?
AdvancedGenerator expressions create iterators using syntax (expression for item in iterable if condition). Similar to list comprehension but more memory efficient for large datasets as they generate values on-the-fly instead of storing all at once.
42. Explain the difference between deep and shallow copy.
ModerateShallow copy creates new object but references same nested objects (copy.copy()). Deep copy creates new object and recursively copies nested objects (copy.deepcopy()). Choose based on whether nested objects need independent copies.
43. What are magic methods (dunder methods) in Python?
AdvancedMagic methods are special methods with double underscores (e.g., __init__, __str__) that define behavior for operations like initialization, string representation, comparison, arithmetic. They customize class behavior and operator overloading.
44. How does Python handle memory management?
AdvancedPython uses private heap space for memory management. Memory manager allocates heap space for objects. Reference counting tracks object usage. Memory pool for small objects improves allocation speed. Garbage collector frees unused memory.
45. What are the different ways to handle conditional execution?
BasicPython offers if/elif/else statements, ternary operators (value_if_true if condition else value_if_false), and conditional expressions. Also supports match/case (3.10+) for pattern matching and boolean short-circuit evaluation.
46. How do you use walrus operator (:=) and what are its benefits?
AdvancedWalrus operator assigns values in expressions: while (n := len(a)) > 0. Benefits include more concise code, avoiding repetitive expressions, and combining assignment with conditional checks. Introduced in Python 3.8.
47. What are the different loop control statements in Python?
BasicPython provides break (exit loop), continue (skip to next iteration), else (executes when loop completes normally), and pass (null statement) for loop control. Can be used in both for and while loops.
48. How does Python handle variable assignment and reference?
ModeratePython assigns references to objects, not objects themselves. Multiple names can reference same object. Assignment creates new reference, not copy. Understanding this is crucial for mutable vs immutable objects behavior.
49. What are sequence unpacking and packing in Python?
ModerateUnpacking assigns sequence elements to variables: a, b = [1, 2]. Packing collects multiple values into sequence using *args for positional and **kwargs for keyword arguments. Supports extended unpacking with * operator.
50. How do you handle string encoding and decoding in Python?
AdvancedUse encode() to convert string to bytes, decode() for bytes to string. Specify encoding (e.g., 'utf-8', 'ascii'). Handle encoding errors with error handlers like 'ignore', 'replace', 'strict'. Important for file I/O and network operations.
51. What are the differences between range, xrange (Python 2), and range (Python 3)?
ModeratePython 2's range creates list, xrange creates iterator. Python 3's range creates range object (iterator-like). Range object more memory efficient as it generates values on demand rather than storing all in memory.
52. How do you handle boolean operations and short-circuit evaluation?
BasicBoolean operations (and, or, not) follow short-circuit rules. 'and' returns first false value or last value, 'or' returns first true value or last value. Short-circuiting optimizes evaluation by skipping unnecessary checks.
53. What are f-strings and their advanced features?
ModerateF-strings (formatted string literals) allow embedding expressions: f'{var=}'. Support format specifiers, multiline strings, expressions, and = specifier for debugging. More readable and performant than older formatting methods.
54. How does Python handle integer division and floating-point arithmetic?
Moderate/ performs true division (returns float), // performs floor division (returns int for ints). Floating-point follows IEEE 754. Be aware of floating-point precision issues and decimal module for exact decimal arithmetic.
55. What are the different ways to comment Python code?
BasicUse # for single-line comments, triple quotes (''' or """) for multiline comments/docstrings. Docstrings document modules, classes, methods. Comments explain why, not what. Follow PEP 257 for docstring conventions.
56. How do you use match statements (pattern matching) in Python?
AdvancedMatch statements (3.10+) provide pattern matching: match value: case pattern: .... Supports patterns like literals, sequences, mappings, classes. More powerful than switch statements in other languages.
57. What are the naming conventions in Python?
BasicFollow PEP 8: lowercase_with_underscores for functions/variables, CapitalizedWords for classes, _single_leading_underscore for internal use, __double_leading_underscore for name mangling, UPPERCASE for constants.
58. How does Python handle operator precedence?
ModeratePython follows operator precedence: exponentiation highest, then multiplication/division, then addition/subtraction. Parentheses override precedence. Bitwise operators have specific precedence. Important for complex expressions.
59. What are the different number systems and their representation in Python?
ModerateSupport binary (0b), octal (0o), hexadecimal (0x) literals. Convert between bases using bin(), oct(), hex(), int(str, base). Important for bit manipulation and low-level operations.