Category 1: Python Basics & Syntax
1. What is the difference between List and Tuple?
Lists are mutable (changeable) and denoted by square brackets []. Tuples are immutable (unchangeable), denoted by parentheses (), and are generally faster and memory-efficient.
2. How is Python interpreted?
Python code is compiled into bytecode (.pyc files), which is then executed by the Python Virtual Machine (PVM). It is not compiled into machine code directly like C++.
3. What is PEP 8?
PEP 8 is the official style guide for Python code. It recommends coding conventions like 4-space indentation, variable naming (snake_case), and line length limits to ensure readability.
4. What is the difference between is and ==?
The == operator checks for value equality (do objects look the same?). The is operator checks for reference identity (do both point to the exact same memory location?).
5. How do you manage memory in Python?
Python uses a private heap space managed by the Memory Manager. It utilizes reference counting and a built-in Garbage Collector to recycle memory when objects are no longer referenced.
6. What are Python namespaces?
A namespace is a system ensuring that all names in a program are unique and can be used without conflict. Examples include Local, Enclosing, Global, and Built-in namespaces (LEGB rule).
7. What is type conversion in Python?
It is the conversion of one data type into another. Implicit conversion is done automatically by Python (e.g., int to float), while Explicit conversion (Type Casting) is done using functions like int(), str().
8. What is the difference between .py and .pyc files?
.py contains the source code written by the programmer. .pyc contains the compiled bytecode generated by the interpreter to speed up execution in subsequent runs.
9. What are the built-in mutable and immutable types?
Mutable: Lists, Sets, Dictionaries.
Immutable: Strings, Tuples, Numbers (Int, Float, Complex), Frozensets.
10. What is a Docstring?
A docstring is a string literal that occurs as the first statement in a module, function, or class definition. It is accessed via the __doc__ attribute and is used for documentation.
Category 2: Data Structures
11. How does a Dictionary work internally?
Dictionaries use Hash Tables. Keys are hashed using a hash function, and the result determines the memory bucket where the value is stored, allowing
O(1)O(1)
average lookup time.
12. What is the difference between append() and extend()?
append() adds a single element to the end of a list. extend() iterates over an iterable (like another list) and appends each element individually to the list.
13. What is a Set and when would you use it?
A Set is an unordered collection of unique elements. It is used when you need to remove duplicates from a list or perform mathematical set operations like union and intersection.
14. What is a frozen set?
A frozenset is an immutable version of a Python set. Because it is immutable, it can be used as a key in a dictionary, whereas a standard set cannot.
15. What is slicing?
Slicing is a mechanism to extract a range of items from sequence types (strings, lists, tuples) using the syntax [start:stop:step].
16. How do you reverse a list?
You can use the built-in .reverse() method (modifies in-place), the slicing trick [::-1] (creates a copy), or the reversed() function (returns an iterator).
17. What is the difference between del, remove(), and pop()?
del removes an item by index or deletes the variable. remove() deletes the first occurrence of a specific value. pop() removes and returns an item at a specific index (default is last).
18. What is Dictionary Comprehension?
It is a concise way to create dictionaries from iterables. Syntax: {key: value for vars in iterable}. Example: {x: x**2 for x in range(5)}.
19. How do you sort a dictionary by value?
Use sorted() with a lambda key. Example: sorted(my_dict.items(), key=lambda item: item[1]). This returns a list of tuples sorted by value.
20. What is collections.defaultdict?
It is a dictionary subclass that provides a default value for a nonexistent key, preventing KeyError. You must specify a factory function (like int or list) upon creation.
Category 3: Functions & Functional Programming
21. What is the difference between *args and **kwargs?
*args allows passing a variable number of positional arguments (received as a tuple). **kwargs allows passing a variable number of keyword arguments (received as a dictionary).
22. What is a Lambda function?
A lambda is an anonymous, single-line function defined with the lambda keyword. It can take any number of arguments but can only have one expression.
23. What are map, filter, and reduce?
map: Applies a function to all items in an input list.
filter: Creates a list of elements for which a function returns true.
reduce: Performs a rolling computation to sequential pairs of values in a list (needs functools).
24. What is Scope resolution (LEGB Rule)?
Python looks for variables in this order: Local, Enclosing (nested functions), Global (module level), and Built-in (Python keywords).
25. What is the difference between yield and return?
return sends a specified value back to its caller and terminates the function. yield produces a sequence of values over time, pausing the function execution and maintaining its state (creating a Generator).
26. What is a First Class function?
In Python, functions are first-class objects. This means they can be assigned to variables, passed as arguments to other functions, and returned from other functions.
27. What is a recursive function?
A function that calls itself is recursive. It must have a base case to stop the recursion and prevent a RecursionError (stack overflow).
28. What is a Closure?
A closure is a nested function that remembers and has access to variables in the enclosing scope (non-local variables) even after the enclosing function has finished executing.
29. What is partial application (functools.partial)?
It allows you to fix a certain number of arguments of a function and generate a new function. It is useful for freezing arguments for callbacks.
30. Does Python pass by value or reference?
Python passes "Object References by Value." If you pass a mutable object, changes inside the function reflect outside. If you pass an immutable object, the function cannot change the original object.
Category 4: Object-Oriented Programming (OOP)
31. What is __init__?
It is the constructor method in Python. It is automatically called when a new instance (object) of a class is created to initialize attributes.
32. What is self?
self represents the instance of the class. It binds the attributes with the given arguments. It is explicitly included as the first parameter in instance methods.
33. What is the difference between __init__ and __new__?
__new__ is a static method that creates the object instance and returns it. __init__ initializes the object after it is created. __new__ is rarely used except in metaclasses.
34. What is Inheritance?
Inheritance allows a class (child) to derive attributes and methods from another class (parent), promoting code reuse. Python supports single, multiple, and multilevel inheritance.
35. What is the MRO (Method Resolution Order)?
MRO determines the order in which Python searches for a method in a hierarchy of classes. Python uses the C3 Linearization algorithm to determine this (usually: Child -> Parent -> Grandparent).
36. What are Class methods vs Static methods?
@classmethod: Takes cls as the first param; can modify class state.
@staticmethod: Takes no specific first param; acts like a regular function strictly belonging to the class namespace.
37. What is Encapsulation?
It is the bundling of data and methods into a single unit (class) and restricting access. In Python, "private" variables are denoted by a double underscore prefix __var (Name Mangling).
38. What is Polymorphism?
The ability of different objects to respond to the same method call in different ways. For example, the + operator works differently for integers (addition) and strings (concatenation).
39. What are Magic (Dunder) Methods?
Special methods surrounded by double underscores (e.g., __str__, __len__, __add__). They allow you to define how objects behave with built-in operations like printing or addition.
40. What is an Abstract Base Class (ABC)?
Defined in the abc module, ABCs allow you to define methods that must be implemented within any child class, enforcing a strict interface.
Category 5: Advanced Python
41. What is a Decorator?
A decorator is a design pattern that allows you to modify the behavior of a function or class without changing its source code. It wraps the original function.
42. How does a Generator work?
Generators are iterators that generate values on the fly using yield. They are memory efficient because they do not store the entire sequence in memory at once.
43. What is an Iterator?
An object that implements __iter__() and __next__(). It enables traversing through a container (like lists) sequentially.
44. What is a Context Manager (with statement)?
It manages resources (like file streams or database connections) to ensure they are properly acquired and released. It uses __enter__ and __exit__ methods.
45. What is Monkey Patching?
Monkey patching is the dynamic modification of a class or module at runtime. It is often used in testing to mock behavior but can lead to code that is hard to debug.
46. What are Metaclasses?
A metaclass is a "class of a class." It defines how a class behaves. Just as an object is an instance of a class, a class is an instance of a metaclass (default is type).
47. What is the Global Interpreter Lock (GIL)?
The GIL is a mutex that prevents multiple native threads from executing Python bytecodes at once. This makes standard Python threads CPU-bound but safe for memory management.
48. What is Shallow Copy vs Deep Copy?
Shallow: Creates a new object but inserts references to the items found in the original.
Deep: Creates a new object and recursively copies everything found in the original (independent copy).
49. What are Descriptors?
Objects that define __get__, __set__, or __delete__. They provide the underlying logic for properties, methods, and static methods.
50. How do you profile Python code?
You can use the cProfile module to measure execution time of functions, or timeit for small snippets. Memory profiling can be done using memory_profiler.
Category 6: Error Handling & File Handling
51. What is the difference between except Exception and except BaseException?
BaseException is the root of all exceptions (including SystemExit). Exception is the base class for non-fatal code errors. You should usually catch Exception to avoid stopping system exits.
52. What is the finally block?
Code in the finally block always executes, regardless of whether an exception occurred or not. It is typically used for cleanup actions (closing files/connections).
53. How do you create a custom Exception?
Create a new class that inherits from the built-in Exception class. You can override __init__ to accept custom error codes or messages.
54. What is pickling and unpickling?
Pickling (pickle module) is serializing an object into a byte stream. Unpickling is deserializing the byte stream back into a Python object.
55. How do you handle JSON in Python?
Use the json library. json.dumps() converts a dictionary to a JSON string. json.loads() converts a JSON string into a Python dictionary.
Category 7: Concurrency & Parallelism
56. Threads vs Processes in Python?
Threads share the same memory space and are limited by the GIL (good for I/O tasks). Processes have separate memory spaces and bypass the GIL (good for CPU-heavy tasks).
57. What is asyncio?
A library to write concurrent code using the async / await syntax. It uses a single-threaded event loop to handle I/O-bound tasks efficiently without threading overhead.
58. What is a Race Condition?
It occurs when two threads access a shared variable simultaneously, leading to unpredictable results. It is prevented using Locks (threading.Lock) or Semaphores.
59. What is a Daemon Thread?
A background thread that automatically dies when the main program exits. It is used for background tasks like garbage collection or keeping alive sessions.
60. What is multiprocessing.Queue?
A thread and process-safe queue used for communication/data exchange between different processes in the multiprocessing module.
Category 8: Libraries & Ecosystem (Pandas, NumPy, Web)
61. What is the difference between NumPy Arrays and Lists?
NumPy arrays are stored in contiguous memory, making them significantly faster and more compact than Python Lists, and they support vectorized operations.
62. What is a DataFrame?
A 2-dimensional labeled data structure in Pandas (like a SQL table or Excel sheet). It consists of rows and columns and supports heterogeneous data.
63. What is pip?
PIP is the standard package manager for Python. It installs packages from the Python Package Index (PyPI) and other indexes.
64. What is a Virtual Environment?
An isolated environment that creates a specific folder for project dependencies. It ensures libraries installed for one project do not conflict with system libraries or other projects.
65. Django vs Flask?
Django is a "batteries-included" full-stack framework (ORM, Auth, Admin included). Flask is a micro-framework (minimalistic, requires extensions for DB/Auth), offering more flexibility.
Category 9: Testing & Debugging
66. What is Unit Testing?
Testing individual units of source code (functions/methods) to determine if they are fit for use. Python uses the unittest or pytest frameworks.
67. What is Mocking?
Replacing real objects (like API calls or DB connections) with mock objects during testing to isolate the code being tested and ensure speed/reliability.
68. What is PDB?
PDB is the Python Debugger. It allows you to pause execution, inspect variables, and step through code line-by-line using import pdb; pdb.set_trace().
69. What are Assertions?
Debugging tools used to test a condition. If the condition is True, the program continues; if False, it raises an AssertionError.
70. What is a linter (e.g., Pylint/Flake8)?
A static code analysis tool that flags programming errors, bugs, stylistic errors, and suspicious constructs before the code is actually run.
Category 10: Miscellaneous & Tricky Questions
71. What does if __name__ == "__main__": do?
It ensures that the code block inside is executed only when the script is run directly, not when it is imported as a module in another script.
72. Why are default mutable arguments dangerous?
Default arguments are evaluated only once at function definition. If you use a mutable default (like []), changes persist across multiple function calls.
73. What is __slots__?
A magic attribute that restricts the creation of dynamic attributes in a class to save memory. It prevents the creation of __dict__ for each instance.
74. How does garbage collection work with circular references?
Reference counting fails with circular references (A -> B -> A). Python's cyclic garbage collector periodically scans for groups of objects that are unreachable from outside and deletes them.
75. What is the pass statement?
A null statement. It does nothing when executed. It is used as a placeholder in loops, functions, or classes where empty code is not allowed syntactically.
76. What is the ternary operator syntax in Python?
value_if_true if condition else value_if_false. Example: status = "Adult" if age >= 18 else "Minor".
77. What is String Interpolation (f-strings)?
Introduced in Python 3.6, f-strings (f"Hello {name}") provide a concise, readable, and fast way to embed expressions inside string literals.
78. What is zip()?
It takes iterables (can be zero or more), makes an iterator that aggregates elements based on the iterables passed, and returns an iterator of tuples.
79. What is the with statement equivalent to in try/finally?
with open('file') as f: is roughly equivalent to f = open('file'); try: ... finally: f.close(). It guarantees cleanup.
80. What is the difference between range() (Py3) and xrange() (Py2)?
In Python 2, range created a list, while xrange created an iterator. In Python 3, range is an iterator (like the old xrange), and xrange was removed.
