1. What is Python, and why is it popular?
Python is a high-level, interpreted programming language known for its simplicity and readability. Its popularity stems from versatile applications in web development, data science, automation, and AI, supported by a vast ecosystem of libraries like pandas and TensorFlow.
2. What are the key features of Python?
Python features include dynamic typing, object-oriented and functional programming support, and a clear syntax that enhances readability. It also offers extensive standard libraries, cross-platform compatibility, and strong community support.
3. What is the difference between Python 2 and Python 3?
Python 3 introduced breaking changes like Unicode strings, print as a function, and integer division returning floats. Python 2 is no longer supported since 2020, making Python 3 the standard with improved features and security.
4. What is a dynamically typed language?
In a dynamically typed language like Python, variable types are determined at runtime, not compile-time. This allows flexibility, as you don’t declare types, but requires careful error handling to avoid type-related issues.
5. What is PEP 8?
PEP 8 is Python’s style guide, outlining coding conventions for consistent, readable code. It covers naming conventions, indentation (4 spaces), and line length (79 characters) to improve collaboration and maintainability.
6. What is the difference between a list and a tuple in Python?
A list is mutable, allowing modifications like adding or removing elements, while a tuple is immutable, fixed after creation. Tuples are faster and used for constant data, while lists suit dynamic collections.
7. What is a dictionary in Python?
A dictionary is a mutable, unordered collection of key-value pairs, where keys are unique and immutable. It provides fast lookups using hash tables, ideal for mapping data like phonebooks or configurations.
8. What are sets in Python?
Sets are unordered collections of unique, immutable elements, supporting operations like union, intersection, and difference. They’re useful for removing duplicates or checking membership efficiently.
9. What is the difference between `append()` and `extend()` in Python lists?
`append()` adds a single element to the end of a list, treating it as one item, while `extend()` adds each element of an iterable individually. For example, `list.append([1,2])` adds `[1,2]`, but `list.extend([1,2])` adds `1` and `2`.
10. What is a list comprehension in Python?
A list comprehension is a concise way to create lists using a single line, like `[x*2 for x in range(5)]`. It’s faster than loops and improves readability for simple transformations or filtering.
11. What is a generator in Python?
A generator is an iterator that yields values one at a time, defined using `yield` in a function or a generator expression. It saves memory by generating values on-demand, ideal for large datasets.
12. What is the difference between a generator and a list comprehension?
A list comprehension creates an entire list in memory, while a generator yields values one by one, conserving memory. Generators are suited for iterating over large or infinite sequences.
13. What is the `yield` keyword in Python?
`yield` pauses a function’s execution, returning a value to the caller while preserving the function’s state. It’s used in generators to produce values lazily, improving memory efficiency.
14. What is a lambda function in Python?
A lambda function is an anonymous, single-expression function defined with `lambda`, like `lambda x: x*2`. It’s used for short, inline operations, often with functions like `map()` or `filter()`.
15. What is the difference between `map()` and `filter()` in Python?
`map()` applies a function to each item in an iterable, returning a transformed iterable, while `filter()` selects items based on a function returning `True` or `False`. Both return iterators in Python 3.
16. What is the `reduce()` function in Python?
`reduce()`, from `functools`, applies a function cumulatively to an iterable’s items, reducing it to a single value, like summing numbers. It’s less common since list comprehensions or loops are often clearer.
17. What is the difference between `range()` and `xrange()`?
`range()` in Python 3 returns a range object, generating numbers on-demand, while `xrange()` in Python 2 is its equivalent but deprecated. Python 3’s `range()` is memory-efficient like `xrange()`.
18. What is the purpose of the `pass` statement in Python?
`pass` is a no-operation placeholder used when a statement is syntactically required but no action is needed. It’s common in empty loops, functions, or class definitions during development.
19. What are Python’s built-in data types?
Python’s built-in data types include numeric (int, float, complex), sequence (list, tuple, string), mapping (dict), set (set, frozenset), and boolean (True, False). Each serves specific use cases like collections or calculations.
20. What is the difference between mutable and immutable objects?
Mutable objects, like lists and dictionaries, can be modified after creation, while immutable objects, like tuples and strings, cannot. Immutability ensures data consistency but requires new objects for changes.
21. What is the `global` keyword in Python?
`global` declares a variable in a function as global, allowing modification of a variable outside the function’s scope. It’s used to avoid creating a local variable with the same name.
22. What is the `nonlocal` keyword in Python?
`nonlocal` allows a nested function to modify a variable in its enclosing function’s scope, not the global scope. It’s useful for closures where inner functions need to update outer variables.
23. What is the difference between shallow copy and deep copy?
A shallow copy creates a new object but references nested objects, so changes to nested objects affect the original. A deep copy creates a fully independent copy, including all nested objects, using `copy.deepcopy()`.
24. What is the `copy` module in Python?
The `copy` module provides functions for shallow (`copy.copy()`) and deep (`copy.deepcopy()`) copying of objects. It’s used to duplicate complex data structures without unintended side effects.
25. What is a decorator in Python?
A decorator is a function that wraps another function to extend its behavior without modifying its code, using the `@` syntax. It’s commonly used for logging, authentication, or timing functions.
26. How do you create a decorator in Python?
Define a wrapper function that takes a function as an argument, adds functionality, and returns the wrapped function. Use `@decorator_name` above the target function to apply it.
27. What is the `@property` decorator in Python?
`@property` turns a method into a getter, allowing attribute-like access to methods without parentheses. It’s used with `@setter` and `@deleter` for controlled attribute management.
28. What is a closure in Python?
A closure is a nested function that retains access to its enclosing function’s variables, even after the outer function finishes. It’s used to maintain state, like counters or configurations.
29. What is the difference between a function and a method in Python?
A function is a standalone procedure defined with `def`, while a method is a function bound to a class or instance. Methods take `self` as their first parameter in classes.
30. What is the `self` parameter in Python?
`self` refers to the instance calling a method in a class, allowing access to instance attributes and methods. It’s explicitly included as the first parameter in instance methods.
31. What is the difference between `__init__` and `__new__` in Python?
`__new__` creates and returns a new instance of a class, called before `__init__`. `__init__` initializes the instance by setting attributes after it’s created.
32. What is a class in Python?
A class is a blueprint for creating objects, defining attributes and methods that describe the object’s behavior and state. It’s defined using the `class` keyword.
33. What is inheritance in Python?
Inheritance allows a class to inherit attributes and methods from another class, promoting code reuse. The child class can override or extend the parent class’s functionality.
34. What is multiple inheritance in Python?
Multiple inheritance allows a class to inherit from multiple parent classes, combining their attributes and methods. Python resolves method conflicts using the Method Resolution Order (MRO).
35. What is the Method Resolution Order (MRO)?
MRO determines the order in which Python searches for methods in a class hierarchy, especially in multiple inheritance. It follows the C3 linearization algorithm, viewable via `__mro__`.
36. What is a static method in Python?
A static method, defined with `@staticmethod`, belongs to a class but doesn’t access instance or class data. It’s used for utility functions related to the class.
37. What is a class method in Python?
A class method, defined with `@classmethod`, takes the class as its first parameter (`cls`) and can access or modify class state. It’s used for factory methods or class-level operations.
38. What is the difference between `@staticmethod` and `@classmethod`?
`@staticmethod` doesn’t take `self` or `cls`, acting like a regular function within a class, while `@classmethod` takes `cls` to access class attributes. Class methods are more flexible for class-level logic.
39. What is encapsulation in Python?
Encapsulation hides a class’s internal data, exposing only necessary parts via methods. Python uses naming conventions like `_protected` and `__private` to indicate access restrictions, though not strictly enforced.
40. What is polymorphism in Python?
Polymorphism allows different classes to be treated as instances of a common interface, using methods with the same name but different implementations. It’s achieved through method overriding or duck typing.
41. What is duck typing in Python?
Duck typing allows objects to be used based on their behavior (methods/attributes) rather than their type, following “if it walks like a duck.” It enables flexible, dynamic polymorphism.
42. What is an abstract base class (ABC) in Python?
An abstract base class, defined using the `abc` module, cannot be instantiated and requires subclasses to implement abstract methods. It enforces a contract for subclasses, ensuring consistent interfaces.
43. How do you create an abstract method in Python?
Use the `@abstractmethod` decorator from the `abc` module in an abstract base class. Subclasses must implement the method, or they can’t be instantiated.
44. What is the `super()` function in Python?
`super()` accesses methods or attributes from a parent class in a child class, often used in `__init__` to call the parent’s constructor. It supports proper inheritance in single or multiple inheritance.
45. What is a mixin in Python?
A mixin is a class that provides methods to other classes via inheritance, without being instantiated itself. It’s used to add reusable functionality, like logging or serialization, to multiple classes.
46. What is the difference between `__str__` and `__repr__` in Python?
`__str__` returns a user-friendly string representation of an object, used by `print()`, while `__repr__` returns a developer-friendly, unambiguous string, often for debugging. If `__str__` is missing, `__repr__` is used.
47. What is the `__len__` method in Python?
`__len__` defines the behavior of the `len()` function for a custom class, returning the size of the object. For example, a custom list class might return the number of items.
48. What is the `__getitem__` method in Python?
`__getitem__` enables indexing or slicing for a custom class, like `obj[key]`. It’s used to make objects behave like lists or dictionaries for accessing elements.
49. What is the `__setitem__` method in Python?
`__setitem__` allows assigning values to an indexed or keyed element, like `obj[key]
50. What is the `__del__` method in Python?
`__del__` is a destructor called when an object is about to be garbage-collected, allowing cleanup like closing files. It’s not guaranteed to run, so explicit cleanup is preferred.
51. What is garbage collection in Python?
Garbage collection automatically frees memory by reclaiming objects no longer referenced, using reference counting and a cyclic garbage collector. It manages memory efficiently but can cause pauses in large applications.
52. What is reference counting in Python?
Reference counting tracks the number of references to an object; when it reaches zero, the object is deallocated. It’s Python’s primary memory management mechanism, supplemented by cyclic garbage collection.
53. What is a cyclic garbage collector in Python?
The cyclic garbage collector detects and frees objects involved in reference cycles, where objects reference each other, preventing memory leaks. It’s triggered periodically or manually via `gc.collect()`.
54. What is the `gc` module in Python?
The `gc` module provides an interface to Python’s garbage collector, allowing manual collection (`gc.collect()`) or configuration of collection settings. It’s used for debugging or optimizing memory usage.
55. What is a memory leak in Python?
A memory leak occurs when objects remain in memory despite no references, often due to circular references or improper resource management. Python’s garbage collector mitigates this, but manual checks are needed.
56. What is the difference between `is` and `
`is` checks for identity (same memory location), while `
57. What is the `id()` function in Python?
`id()` returns a unique identifier for an object, typically its memory address, constant during the object’s lifetime. It’s used to check object identity with `is`.
58. What is the `type()` function in Python?
`type()` returns the class or type of an object, like `` for an integer. It’s used for introspection or dynamic type checking in Python.
59. What is the `isinstance()` function in Python?
`isinstance(obj, class)` checks if an object is an instance of a class or its subclasses, supporting inheritance. It’s preferred over `type()` for type checking due to polymorphism.
60. What is the `issubclass()` function in Python?
`issubclass(class, parent)` checks if a class is a subclass of another class or tuple of classes, including itself. It’s used to verify inheritance relationships.
61. What is the `dir()` function in Python?
`dir()` returns a list of valid attributes and methods for an object, useful for introspection. Without arguments, it lists the current scope’s names.
62. What is the `help()` function in Python?
`help()` provides interactive documentation for modules, classes, or functions, displaying their docstrings and details. It’s useful for exploring Python objects during development.
63. What is a docstring in Python?
A docstring is a string literal placed as the first statement in a module, class, or function, describing its purpose. It’s accessible via `__doc__` and used by tools like `help()`.
64. What is the difference between a module and a package in Python?
A module is a single `.py` file containing Python code, while a package is a directory of modules with an `__init__.py` file. Packages organize related modules hierarchically.
65. What is the `__init__.py` file in Python?
`__init__.py` marks a directory as a Python package, allowing module imports. It can be empty or contain initialization code for the package.
66. What is the `import` statement in Python?
`import` loads modules or packages into the current namespace, enabling access to their functions, classes, or variables. Variants like `from ... import` control scope and naming.
67. What is the difference between `import module` and `from module import *`?
`import module` imports a module, requiring `module.name` to access its contents, while `from module import *` imports all names directly, risking namespace pollution.
68. What is the `sys` module in Python?
The `sys` module provides access to system-specific parameters and functions, like `sys.argv` for command-line arguments or `sys.path` for module search paths.
69. What is the `os` module in Python?
The `os` module provides functions for interacting with the operating system, like file operations (`os.remove()`), directory navigation (`os.getcwd()`), or environment variables (`os.environ`).
70. What is the `pathlib` module in Python?
`pathlib` provides an object-oriented approach to handle file system paths, like `Path(\'file.txt\')`, across platforms. It’s more intuitive than `os.path` for path manipulations.
71. What is the `time` module in Python?
The `time` module provides functions for time-related operations, like `time.time()` for current timestamp or `time.sleep()` for pausing execution. It’s used for timing or scheduling.
72. What is the `datetime` module in Python?
The `datetime` module handles date and time operations, like creating `datetime` objects, parsing strings, or calculating differences. It’s more robust than `time` for complex date tasks.
73. What is the `random` module in Python?
The `random` module generates pseudo-random numbers, with functions like `random.randint()` for integers or `random.choice()` for selecting items. It’s used for simulations or shuffling.
74. What is the `math` module in Python?
The `math` module provides mathematical functions and constants, like `math.sqrt()` for square roots or `math.pi` for π. It’s used for numeric computations beyond basic operators.
75. What is the `re` module in Python?
The `re` module supports regular expressions for pattern matching, like `re.search()` to find substrings or `re.sub()` to replace patterns. It’s powerful for text processing.
76. What is a regular expression in Python?
A regular expression is a pattern for matching strings, like `\\d+` for digits, used with the `re` module. It enables complex text searches, validation, or substitutions.
77. What is the `json` module in Python?
The `json` module handles JSON data, with `json.loads()` to parse JSON strings and `json.dumps()` to serialize Python objects. It’s used for APIs and data interchange.
78. What is the `csv` module in Python?
The `csv` module reads and writes CSV files, with `csv.reader()` for parsing rows and `csv.writer()` for creating files. It handles delimiters and quoting automatically.
79. What is the `pickle` module in Python?
The `pickle` module serializes and deserializes Python objects, like lists or classes, to/from binary files. It’s used for saving complex data but isn’t secure for untrusted sources.
80. What is the difference between `pickle` and `json` in Python?
`pickle` serializes arbitrary Python objects to binary, supporting complex types but lacking security, while `json` produces human-readable text, limited to basic types but safer for interchange.
81. What is the `logging` module in Python?
The `logging` module provides a flexible system for recording messages, with levels like DEBUG or ERROR, to files or consoles. It’s preferred over `print()` for production code.
82. What is the `argparse` module in Python?
The `argparse` module parses command-line arguments, defining options and flags with `ArgumentParser`. It simplifies building user-friendly CLI applications with help messages.
83. What is the `unittest` module in Python?
The `unittest` module supports unit testing, allowing you to write test cases with `TestCase` classes and assertions like `assertEqual()`. It ensures code reliability through automated tests.
84. What is the `pytest` framework in Python?
`pytest` is a third-party testing framework that simplifies writing and running tests with minimal boilerplate. It supports fixtures, parameterized tests, and detailed reporting.
85. What is a fixture in `pytest`?
A fixture in `pytest` is a setup/teardown function, marked with `@pytest.fixture`, providing reusable test resources like database connections. It’s requested by test functions via parameters.
86. What is the difference between `unittest` and `pytest`?
`unittest` is Python’s built-in testing framework with verbose syntax, while `pytest` is simpler, supports plugins, and auto-discovers tests. `pytest` is preferred for its flexibility and readability.
87. What is the `mock` module in Python?
The `mock` module, part of `unittest.mock`, creates mock objects to simulate behavior of real objects in tests. It’s used to isolate code and test interactions without dependencies.
88. What is a context manager in Python?
A context manager handles setup and cleanup, typically used with `with` statements, like opening files. It’s defined using `__enter__` and `__exit__` or the `contextlib` module.
89. What is the `contextlib` module in Python?
The `contextlib` module provides utilities for creating context managers, like `@contextmanager` for generator-based managers. It simplifies resource management without defining a full class.
90. What is the `with` statement in Python?
The `with` statement ensures proper resource management, like opening and closing files, by invoking a context manager. It reduces boilerplate and handles exceptions automatically.
91. What is exception handling in Python?
Exception handling uses `try`, `except`, `else`, and `finally` to manage errors, preventing crashes. For example, `except ValueError` catches invalid input, while `finally` runs cleanup code.
92. What is the `raise` statement in Python?
`raise` triggers an exception manually, like `raise ValueError(\"Invalid input\")`. It’s used to signal errors or propagate exceptions in custom logic.
93. What is a custom exception in Python?
A custom exception is a user-defined error class inheriting from `Exception`, like `class MyError(Exception): pass`. It’s used to handle specific error conditions in applications.
94. What is the `try-except-else` block in Python?
`try-except-else` runs code in `try`, catches errors in `except`, and executes `else` if no exception occurs. `else` clarifies code that runs only on success.
95. What is the `finally` block in Python?
`finally` runs code regardless of whether an exception occurs in a `try-except` block, ensuring cleanup like closing files. It’s executed before leaving the block.
96. What is a `ZeroDivisionError` in Python?
`ZeroDivisionError` is raised when dividing a number by zero, like `1/0`. It’s caught with `except ZeroDivisionError` to handle invalid arithmetic operations.
97. What is a `TypeError` in Python?
`TypeError` occurs when an operation involves incompatible types, like adding a string and integer. It’s caught with `except TypeError` to validate input types.
98. What is a `ValueError` in Python?
`ValueError` is raised when a function receives an argument of the correct type but an invalid value, like `int(\"abc\")`. It’s used for input validation.
99. What is a `KeyError` in Python?
`KeyError` occurs when accessing a non-existent key in a dictionary, like `dict[\"missing\"]`. It’s caught with `except KeyError` or checked with `dict.get()`.
100. What is an `IndexError` in Python?
`IndexError` is raised when accessing an index outside a sequence’s range, like `list[10]` for a 5-item list. It’s caught with `except IndexError` to validate indices.
101. What is the `assert` statement in Python?
`assert` checks a condition and raises `AssertionError` if false, like `assert x > 0`. It’s used for debugging or enforcing invariants, disabled in optimized mode.
102. What is a `NameError` in Python?
`NameError` occurs when using an undefined variable or function, like referencing `x` before assignment. It’s caught with `except NameError` or avoided with proper scoping.
103. What is the `globals()` function in Python?
`globals()` returns a dictionary of the current global namespace, containing variables and their values. It’s used for introspection or dynamic variable access, though rarely in practice.
104. What is the `locals()` function in Python?
`locals()` returns a dictionary of the current local namespace, like variables in a function. It’s used for debugging but shouldn’t be modified directly.
105. What is a `SyntaxError` in Python?
`SyntaxError` occurs when code violates Python’s grammar, like missing colons or incorrect indentation. It’s caught at compile-time, requiring code correction before execution.
106. What is an `IndentationError` in Python?
`IndentationError` is raised when code has inconsistent or incorrect indentation, like mixing tabs and spaces. Python requires consistent indentation (usually 4 spaces).
107. What is the `eval()` function in Python?
`eval()` executes a string as Python code, returning the result, like `eval(\"1 + 2\")` yielding `3`. It’s risky for untrusted input due to security concerns.
108. What is the `exec()` function in Python?
`exec()` executes a string as Python code, like a script, but doesn’t return a value, unlike `eval()`. It’s used for dynamic code but poses security risks.
109. What is the difference between `eval()` and `exec()`?
`eval()` evaluates a single expression and returns its result, while `exec()` executes arbitrary code, like loops or definitions, without returning a value. Both are unsafe for untrusted input.
110. What is a `metaclass` in Python?
A metaclass is a class of a class, controlling class creation, defined by inheriting from `type`. It’s used for advanced customization, like enforcing class properties or singleton patterns.
111. What is the `type` metaclass in Python?
`type` is the default metaclass for all classes, responsible for creating class objects. It can be subclassed to create custom metaclasses for modifying class behavior.
112. What is the `__metaclass__` attribute in Python?
`__metaclass__` specifies a custom metaclass for a class in Python 2 or at the module level. In Python 3, it’s defined using `class MyClass(metaclass
113. What is a singleton pattern in Python?
A singleton pattern ensures a class has only one instance, often implemented using a metaclass or module-level instance. It’s used for shared resources like database connections.
114. What is the `itertools` module in Python?
The `itertools` module provides efficient tools for working with iterators, like `itertools.chain()` for combining iterables or `itertools.permutations()` for generating permutations.
115. What is the `collections` module in Python?
The `collections` module offers specialized data structures, like `namedtuple` for lightweight classes, `deque` for fast queues, or `Counter` for counting elements.
116. What is a `namedtuple` in Python?
`namedtuple`, from `collections`, creates tuple subclasses with named fields, like `Point
117. What is a `deque` in Python?
`deque`, from `collections`, is a double-ended queue supporting fast appends and pops from both ends. It’s used for queues or stacks in performance-critical applications.
118. What is a `Counter` in Python?
`Counter`, from `collections`, counts hashable objects, like `Counter([\'a\', \'b\', \'a\'])` yielding `{\'a\': 2, \'b\': 1}`. It’s used for frequency analysis or histograms.
119. What is the `heapq` module in Python?
The `heapq` module provides heap queue (priority queue) operations, like `heapify()` or `heappush()`, for efficient sorting and priority-based retrieval. It’s used for algorithms like Dijkstra’s.
120. What is the `bisect` module in Python?
The `bisect` module provides functions for inserting and searching in sorted lists, like `bisect.insort()`. It’s efficient for maintaining sorted data without resorting.
121. What is the `functools` module in Python?
The `functools` module provides higher-order functions, like `partial()` for partial function application or `lru_cache` for memoization. It enhances functional programming in Python.
122. What is the `@lru_cache` decorator in Python?
`@lru_cache`, from `functools`, memoizes function results, caching inputs and outputs to speed up recursive or expensive calls. It’s used for dynamic programming or Fibonacci calculations.
123. What is a `partial` function in Python?
`partial`, from `functools`, creates a new function with some arguments pre-filled, like `partial(func, arg1)`. It’s used to simplify function calls with default parameters.
124. What is the `operator` module in Python?
The `operator` module provides functions for Python’s operators, like `operator.add()` for `+`, used in functional programming. It’s often paired with `map()` or `sorted()`.
125. What is the `threading` module in Python?
The `threading` module supports multi-threading, allowing concurrent execution of tasks, like `Thread(target
126. What is the Global Interpreter Lock (GIL) in Python?
The GIL is a mutex that prevents multiple native threads from executing Python bytecode simultaneously, limiting CPU-bound multi-threading. It simplifies memory management but bottlenecks performance.
127. What is the `multiprocessing` module in Python?
The `multiprocessing` module runs separate processes to bypass the GIL, enabling true parallelism for CPU-bound tasks. It uses `Process` or `Pool` for concurrent execution.
128. What is the difference between `threading` and `multiprocessing`?
`threading` runs threads within the same process, limited by the GIL, suitable for I/O-bound tasks. `multiprocessing` uses separate processes, bypassing the GIL, ideal for CPU-bound tasks.
129. What is the `asyncio` module in Python?
The `asyncio` module supports asynchronous programming using `async def` and `await`, managing I/O-bound tasks concurrently. It’s used for high-performance network applications like web servers.
130. What is an `async def` function in Python?
An `async def` function defines an asynchronous coroutine, executed with `await` or run via `asyncio.run()`. It allows non-blocking I/O operations, improving concurrency.
131. What is the `await` keyword in Python?
`await` pauses an `async` function until a coroutine or future completes, yielding control to the event loop. It’s used to handle asynchronous tasks without blocking.
132. What is an event loop in `asyncio`?
An event loop in `asyncio` schedules and runs asynchronous tasks, managing coroutines and I/O events. It’s accessed via `asyncio.get_event_loop()` or `asyncio.run()`.
133. What is the `concurrent.futures` module in Python?
The `concurrent.futures` module provides high-level interfaces for parallelism, like `ThreadPoolExecutor` for threads or `ProcessPoolExecutor` for processes. It simplifies concurrent task management.
134. What is a `Future` object in Python?
A `Future` represents a delayed computation in `asyncio` or `concurrent.futures`, holding results or exceptions. It’s used to track and retrieve asynchronous task outcomes.
135. What is the `socket` module in Python?
The `socket` module provides low-level networking interfaces for creating client-server applications, like TCP or UDP sockets. It’s used for network programming or real-time communication.
136. What is the `requests` library in Python?
The `requests` library simplifies HTTP requests, like GET or POST, with a user-friendly API. It’s widely used for interacting with web APIs or scraping data.
137. What is the `urllib` module in Python?
The `urllib` module, part of the standard library, handles URL operations, like fetching data with `urllib.request`. It’s less intuitive than `requests` but dependency-free.
138. What is the `beautifulsoup4` library in Python?
`beautifulsoup4` parses HTML or XML documents, allowing easy extraction of data like tags or attributes. It’s used for web scraping, often with `requests`.
139. What is the `scrapy` framework in Python?
`scrapy` is a web crawling and scraping framework for extracting structured data from websites. It handles requests, parsing, and pipelines, ideal for large-scale scraping.
140. What is the `pandas` library in Python?
`pandas` provides data structures like `DataFrame` and `Series` for data manipulation and analysis. It’s used for data cleaning, aggregation, and visualization in data science.
141. What is a `DataFrame` in `pandas`?
A `DataFrame` is a 2D table-like structure in `pandas`, with rows and columns, supporting operations like filtering or grouping. It’s the core data structure for data analysis.
142. What is the `numpy` library in Python?
`numpy` provides support for large, multi-dimensional arrays and mathematical functions, like `np.array()` or `np.linalg`. It’s foundational for scientific computing and machine learning.
143. What is the `matplotlib` library in Python?
`matplotlib` creates static, interactive, or animated visualizations, like plots or histograms, with `pyplot`. It’s widely used for data visualization in scientific and analytical tasks.
144. What is the `seaborn` library in Python?
`seaborn` builds on `matplotlib`, offering high-level functions for statistical visualizations, like heatmaps or violin plots. It simplifies creating aesthetically pleasing charts.
145. What is the `scipy` library in Python?
`scipy` extends `numpy` with advanced scientific functions, like optimization, signal processing, or statistical tests. It’s used in engineering, physics, and data science.
146. What is the `sklearn` library in Python?
`sklearn` (scikit-learn) provides machine learning tools, like classification, regression, and clustering algorithms. It’s user-friendly, integrating with `numpy` and `pandas`.
147. What is the `tensorflow` library in Python?
`tensorflow` is a machine learning framework for building and training neural networks, supporting GPU acceleration. It’s used for deep learning tasks like image or text processing.
148. What is the `pytorch` library in Python?
`pytorch` is a deep learning framework with dynamic computation graphs, favored for research due to its flexibility. It’s used for neural networks and integrates with `numpy`.
149. What is the `flask` framework in Python?
`flask` is a lightweight web framework for building web applications, using routes and templates. It’s simple, extensible, and ideal for small to medium projects.
150. What is the `django` framework in Python?
`django` is a high-level web framework with built-in features like ORM, authentication, and admin panels. It’s suited for rapid development of secure, scalable applications.
151. What is the difference between `flask` and `django`?
`flask` is minimal, offering flexibility for small projects, while `django` is feature-rich, with built-in tools for large-scale applications. `django` enforces structure, while `flask` is more customizable.
152. What is an ORM in `django`?
The ORM (Object-Relational Mapping) in `django` maps Python classes to database tables, allowing database operations via Python code. It simplifies queries and schema management.
153. What is a `QuerySet` in `django`?
A `QuerySet` in `django` represents a collection of database query results, supporting chaining operations like filtering or ordering. It’s lazy, executing only when evaluated.
154. What is a `migration` in `django`?
A `migration` in `django` applies schema changes, like adding tables or columns, to the database, generated via `makemigrations`. It’s applied using `migrate`.
155. What is the `fastapi` framework in Python?
`fastapi` is a modern web framework for building APIs with asynchronous support, leveraging `asyncio`. It’s fast, type-safe, and auto-generates OpenAPI documentation.
156. What is the `sqlalchemy` library in Python?
`sqlalchemy` is a SQL toolkit and ORM for database interactions, supporting raw SQL and object-oriented queries. It’s flexible, used in frameworks like `flask`.
157. What is the `psycopg2` library in Python?
`psycopg2` is a PostgreSQL adapter for Python, enabling database connections and queries. It’s used for low-level database operations or with ORMs like `sqlalchemy`.
158. What is the `pymysql` library in Python?
`pymysql` is a MySQL client for Python, allowing direct database connections and queries. It’s used for MySQL interactions in applications or scripts.
159. What is the `redis` library in Python?
The `redis` library connects Python to Redis, an in-memory key-value store, supporting operations like `set` or `get`. It’s used for caching or message queues.
160. What is the `celery` library in Python?
`celery` is a distributed task queue for asynchronous task processing, like sending emails or running computations. It integrates with brokers like Redis or RabbitMQ.
161. What is a `task` in `celery`?
A `task` in `celery` is a Python function marked with `@task`, executed asynchronously by workers. It’s used for background jobs, like processing uploads.
162. What is the `gunicorn` server in Python?
`gunicorn` is a WSGI HTTP server for running Python web applications, like `flask` or `django`, in production. It handles multiple requests efficiently with worker processes.
163. What is the `uwsgi` server in Python?
`uwsgi` is a fast, scalable WSGI server for hosting Python web applications, supporting protocols like HTTP or FastCGI. It’s used for high-performance deployments.
164. What is the `pytest-cov` plugin in Python?
`pytest-cov` is a `pytest` plugin that measures code coverage, reporting which lines are executed during tests. It helps identify untested code paths.
165. What is the `tox` tool in Python?
`tox` automates testing across multiple Python versions and environments, running tests in isolated virtual environments. It ensures compatibility and reproducibility.
166. What is the `virtualenv` module in Python?
`virtualenv` creates isolated Python environments, preventing package conflicts by installing dependencies locally. It’s used for project-specific dependency management.
167. What is the `pipenv` tool in Python?
`pipenv` manages virtual environments and dependencies, combining `pip` and `virtualenv`. It uses `Pipfile` for reproducible builds and simplifies dependency resolution.
168. What is the `poetry` tool in Python?
`poetry` is a dependency and packaging manager, using `pyproject.toml` for project configuration. It simplifies dependency management and publishing Python packages.
169. What is the `pyproject.toml` file in Python?
`pyproject.toml` defines build and dependency configurations for Python projects, used by tools like `poetry` or `flit`. It standardizes project metadata per PEP 518.
170. What is the `setup.py` file in Python?
`setup.py` is a script for packaging Python projects, defining metadata and dependencies for `pip` installation. It’s being replaced by `pyproject.toml` in modern projects.
171. What is a Python wheel?
A wheel is a binary package format (`.whl`) for Python, speeding up installations by pre-compiling dependencies. It’s used with `pip` for efficient distribution.
172. What is the `twine` tool in Python?
`twine` uploads Python packages to PyPI, securely handling wheel or source distributions. It’s preferred over `setup.py upload` for reliability and security.
173. What is PyPI in Python?
PyPI (Python Package Index) is a repository for Python packages, hosting libraries like `numpy` or `requests`. Developers use `pip` to install packages from PyPI.
174. What is a `requirements.txt` file in Python?
`requirements.txt` lists project dependencies with versions, like `requests
175. What is the `black` tool in Python?
`black` is an opinionated code formatter that enforces a consistent style, like line length and quotes, with minimal configuration. It improves code readability and collaboration.
176. What is the `flake8` tool in Python?
`flake8` is a linter that checks Python code for style (PEP 8), errors, and complexity, combining tools like `pycodestyle` and `pyflakes`. It ensures code quality.
177. What is the `pylint` tool in Python?
`pylint` is a static code analyzer that checks for errors, style, and best practices, assigning scores to code. It’s highly configurable but stricter than `flake8`.
178. What is the `mypy` tool in Python?
`mypy` is a static type checker for Python, enforcing type hints to catch type-related errors before runtime. It improves code reliability in large projects.
179. What are type hints in Python?
Type hints annotate variables, arguments, or return types, like `def add(a: int) -> int`, using the `typing` module. They’re optional and checked by tools like `mypy`.
180. What is the `typing` module in Python?
The `typing` module provides constructs like `List`, `Dict`, or `Optional` for type hints, supporting static type checking. It’s essential for annotated, robust code.
181. What is a `Union` type in Python?
`Union`, from `typing`, indicates a variable can be one of multiple types, like `Union[int, str]`. It’s used in type hints for flexible but type-safe code.
182. What is an `Optional` type in Python?
`Optional[T]`, from `typing`, indicates a variable can be type `T` or `None`, like `Optional[str]`. It’s used to annotate nullable values in type hints.
183. What is the `dataclasses` module in Python?
The `dataclasses` module, with `@dataclass`, simplifies class creation by auto-generating methods like `__init__` or `__repr__`. It’s used for structured data with minimal boilerplate.
184. What is a `frozenset` in Python?
`frozenset` is an immutable version of a set, created with `frozenset([1, 2])`, usable as dictionary keys. It supports set operations but cannot be modified.
185. What is the `enum` module in Python?
The `enum` module defines enumerated types, like `class Color(Enum): RED
186. What is the `zip` function in Python?
`zip()` combines multiple iterables into tuples, like `zip([1, 2], [\'a\', \'b\'])` yielding `(1, \'a\'), (2, \'b\')`. It’s used for parallel iteration or dictionary creation.
187. What is the `any()` function in Python?
`any()` returns `True` if any element in an iterable is `True`, like `any([False, True])`. It’s efficient, short-circuiting on the first truthy value.
188. What is the `all()` function in Python?
`all()` returns `True` if all elements in an iterable are `True`, like `all([True, True])`. It short-circuits on the first falsy value for efficiency.
189. What is the `sorted()` function in Python?
`sorted()` returns a new sorted list from an iterable, like `sorted([3, 1, 2])` yielding `[1, 2, 3]`. It supports custom keys via `key
190. What is the `reversed()` function in Python?
`reversed()` returns an iterator of an iterable’s elements in reverse order, like `reversed([1, 2, 3])`. It’s memory-efficient, used with sequences like lists.
191. What is the `slice` object in Python?
A `slice` object, created with `slice(start, stop, step)`, represents a range for slicing, like `list[slice(1, 3)]`. It’s used for reusable or programmatic slicing.
192. What is the ` Ellipsis` (`...`) in Python?
`Ellipsis` (`...`) is a singleton used as a placeholder, often in type hints or `numpy` slicing, like `array[..., 0]`. It’s rarely used in standard Python code.
193. What is the `NotImplemented` constant in Python?
`NotImplemented` is a special value returned by methods like `__eq__` to indicate an operation isn’t supported, letting Python try alternatives. It’s distinct from `NotImplementedError`.
194. What is the `NotImplementedError` in Python?
`NotImplementedError` is raised when an abstract method or unsupported operation is called, signaling it must be implemented in subclasses. It’s used in abstract base classes.
195. What is the `memoryview` object in Python?
`memoryview` provides a view of an object’s memory, like bytes or arrays, without copying, using `memoryview(b\'abc\')`. It’s used for efficient, low-level data manipulation.
196. What is the `bytearray` type in Python?
`bytearray` is a mutable sequence of bytes, like `bytearray(b\'abc\')`, supporting modifications unlike `bytes`. It’s used for binary data manipulation.
197. What is the difference between `bytes` and `bytearray`?
`bytes` is an immutable sequence of bytes, while `bytearray` is mutable, allowing in-place changes. Both store binary data, but `bytearray` is used for dynamic updates.
198. What is the `struct` module in Python?
The `struct` module packs and unpacks binary data into Python types, like `struct.pack(\'i\', 42)` for integers. It’s used for low-level data processing, like network protocols.
199. What is the `array` module in Python?
The `array` module provides a memory-efficient array of basic types, like `array(\'i\', [1, 2])` for integers. It’s faster than lists for large numeric datasets.
200. What is a `weakref` in Python?
A `weakref` creates a weak reference to an object, allowing garbage collection if no strong references remain. It’s used to avoid memory leaks in caching or circular references.
201. What is the `weakref` module in Python?
The `weakref` module supports weak references, with classes like `WeakRef` or `WeakKeyDictionary`. It’s used for memory-efficient structures that don’t prevent garbage collection.
202. What is a `property` in Python?
A `property` manages attribute access with getter, setter, and deleter methods, created via `@property`. It encapsulates data, allowing validation or computed attributes.
203. What is a `descriptor` in Python?
A descriptor is a class with `__get__`, `__set__`, or `__delete__`, controlling attribute access, like `@property`. It’s used for reusable attribute logic in classes.
204. What is the `slots` attribute in Python?
`__slots__` is a class attribute listing allowed instance variables, reducing memory usage by disabling `__dict__`. It’s used for performance in classes with many instances.
205. What is a `coroutine` in Python?
A coroutine is a function defined with `async def`, supporting asynchronous execution with `await`. It’s used in `asyncio` for non-blocking I/O operations.
206. What is a `task` in `asyncio`?
A `task` in `asyncio` is a scheduled coroutine, created with `asyncio.create_task()`, running concurrently in the event loop. It manages asynchronous execution.
207. What is a `future` in `asyncio`?
A `future` in `asyncio` is a placeholder for a result that’s not yet available, used with `await` or callbacks. It’s similar to `concurrent.futures.Future` but for async.
208. What is the `aiohttp` library in Python?
`aiohttp` is an asynchronous HTTP client/server library, built on `asyncio`, for making or serving HTTP requests. It’s used for high-performance web applications.
209. What is the `websockets` library in Python?
`websockets` supports WebSocket communication, enabling real-time, bidirectional data exchange, built on `asyncio`. It’s used for chat apps or live updates.
210. What is the `pyinstaller` tool in Python?
`pyinstaller` bundles Python scripts into standalone executables, including dependencies, for distribution. It’s used to create cross-platform applications without requiring Python.
211. What is the `cProfile` module in Python?
`cProfile` is a built-in profiler that measures function call times and counts, identifying performance bottlenecks. It’s used to optimize Python code.
212. What is the `timeit` module in Python?
`timeit` measures the execution time of small code snippets, running them multiple times for accuracy. It’s used to benchmark and compare performance.
213. What is the `dis` module in Python?
The `dis` module disassembles Python bytecode, showing low-level instructions, like `dis.dis(func)`. It’s used for debugging or understanding code execution.
214. What is a `bytecode` in Python?
Bytecode is an intermediate representation of Python code, generated by the compiler and executed by the Python VM. It’s stored in `.pyc` files for faster loading.
215. What is the `compileall` module in Python?
`compileall` compiles Python source files into bytecode (`.pyc`), improving startup time for modules. It’s used for pre-compiling projects or libraries.
216. What is the `py_compile` module in Python?
`py_compile` compiles a single Python source file into bytecode, creating a `.pyc` file. It’s used for manual compilation or debugging bytecode issues.
217. What is the `marshal` module in Python?
The `marshal` module serializes Python objects into a compact binary format, used internally for `.pyc` files. It’s faster than `pickle` but not for general use.
218. What is the `imp` module in Python?
The `imp` module, deprecated in Python 3.4+, provided functions for dynamic module importing and reloading. It’s replaced by `importlib` for modern code.
219. What is the `importlib` module in Python?
The `importlib` module provides tools for dynamic imports, like `importlib.import_module()`, and module reloading. It’s used for advanced import customization.
220. What is the `pkgutil` module in Python?
The `pkgutil` module supports package utilities, like `pkgutil.iter_modules()` for finding submodules. It’s used for dynamic package discovery or extension.
221. What is the `site` module in Python?
The `site` module customizes Python’s startup, adding site-specific paths to `sys.path` for third-party packages. It runs automatically during Python initialization.
222. What is the `warnings` module in Python?
The `warnings` module manages warning messages, like deprecation notices, with `warn()` or filtering options. It’s used to alert developers without halting execution.
223. What is a `DeprecationWarning` in Python?
`DeprecationWarning` alerts developers about features scheduled for removal in future Python versions. It’s typically ignored in production but visible during development.
224. What is the `atexit` module in Python?
The `atexit` module registers functions to run when a Python program exits normally, like cleanup tasks. It’s used for finalization without exception handling.
225. What is the `tracemalloc` module in Python?
The `tracemalloc` module tracks memory allocations, helping identify memory leaks or usage patterns. It’s used for debugging memory-intensive Python applications.
226. What is the `faulthandler` module in Python?
The `faulthandler` module dumps stack traces on crashes or signals, like segmentation faults, aiding debugging. It’s enabled via `faulthandler.enable()`.
227. What is the `signal` module in Python?
The `signal` module handles OS signals, like `SIGINT` for Ctrl+C, allowing custom handlers with `signal.signal()`. It’s used for graceful shutdowns or event handling.
228. What is a `breakpoint()` in Python?
`breakpoint()` pauses execution and enters the Python debugger (like `pdb`), introduced in Python 3.7. It’s used for interactive debugging without importing `pdb`.
229. What is the `pdb` module in Python?
The `pdb` module is Python’s built-in debugger, allowing step-through execution, breakpoints, and variable inspection. It’s invoked with `pdb.set_trace()` or `breakpoint()`.
230. What is the `ipdb` debugger in Python?
`ipdb` is an enhanced version of `pdb`, adding IPython features like tab completion and syntax highlighting. It’s used for more interactive debugging sessions.
231. What is the `trace` module in Python?
The `trace` module tracks program execution, reporting line-by-line coverage or call graphs. It’s used for debugging or analyzing code flow.
232. What is the `linecache` module in Python?
The `linecache` module reads source code lines efficiently, used by debuggers or tracebacks, like `linecache.getline()`. It caches files for performance.
233. What is a `traceback` in Python?
A traceback is a report of the call stack when an exception occurs, showing the sequence of function calls. It’s printed automatically or accessed via `traceback` module.
234. What is the `inspect` module in Python?
The `inspect` module provides introspection tools, like `inspect.getsource()` for source code or `inspect.signature()` for function details. It’s used for debugging or dynamic analysis.
235. What is the `ast` module in Python?
The `ast` module parses Python code into Abstract Syntax Trees, enabling code analysis or transformation. It’s used for static analysis or code generation.
236. What is the `codeop` module in Python?
The `codeop` module compiles Python code fragments, handling incomplete input for interactive shells. It’s used internally by Python’s REPL.
237. What is the `pyclbr` module in Python?
The `pyclbr` module scans Python source files for class and function definitions without executing them. It’s used for lightweight code analysis or documentation.
238. What is the `profile` module in Python?
The `profile` module provides deterministic profiling of Python programs, measuring function call times. It’s slower than `cProfile` but useful for detailed analysis.
239. What is the `bz2` module in Python?
The `bz2` module provides functions to compress and decompress data using the bzip2 algorithm, like `BZ2File`. It’s used for efficient file compression.
240. What is the `zlib` module in Python?
The `zlib` module supports data compression and decompression using the zlib algorithm, like `zlib.compress()`. It’s used for gzip-compatible compression in files or streams.
241. What is the `gzip` module in Python?
The `gzip` module reads and writes gzip-compressed files, building on `zlib`, like `GzipFile`. It’s used for compressing large datasets or logs.
242. What is the `zipfile` module in Python?
The `zipfile` module creates, reads, and extracts ZIP archives, like `ZipFile(\'archive.zip\')`. It’s used for file compression or bundling.
243. What is the `tarfile` module in Python?
The `tarfile` module handles tar archives, supporting compression like gzip or bzip2, with `TarFile`. It’s used for archiving files or backups.
244. What is the `hashlib` module in Python?
The `hashlib` module provides cryptographic hash functions, like `sha256()` or `md5()`, for data integrity or passwords. It’s used for secure hashing.
245. What is the `hmac` module in Python?
The `hmac` module generates keyed hashes using algorithms like SHA256, ensuring message authenticity. It’s used for secure communication or API signatures.
246. What is the `secrets` module in Python?
The `secrets` module generates cryptographically secure random numbers, like `secrets.token_hex()`. It’s used for secure tokens or passwords, safer than `random`.
247. What is the `uuid` module in Python?
The `uuid` module generates universally unique identifiers, like `uuid.uuid4()` for random IDs. It’s used for unique keys in databases or distributed systems.
248. What is the `base64` module in Python?
The `base64` module encodes and decodes binary data to/from ASCII, like `base64.b64encode()`. It’s used for encoding attachments or API data.
249. What is the `binascii` module in Python?
The `binascii` module converts between binary and ASCII representations, like hex or base64. It’s used for low-level data encoding or checksums.
250. What is the `tempfile` module in Python?
The `tempfile` module creates temporary files and directories, like `TemporaryFile()`, cleaned up automatically. It’s used for transient data in scripts.
251. What is the `shutil` module in Python?
The `shutil` module provides high-level file operations, like `shutil.copy()` or `shutil.rmtree()`, for copying or deleting files. It simplifies file system tasks.
252. What is the `glob` module in Python?
The `glob` module finds files matching patterns, like `glob.glob(\'*.txt\')` for text files. It’s used for file searches in scripts or automation.
253. What is the `fnmatch` module in Python?
The `fnmatch` module matches filenames against Unix-style patterns, like `fnmatch.fnmatch(\'file.txt\', \'*.txt\')`. It’s used with `glob` or for custom filtering.
254. What is the `pathlib` module’s `Path` class?
The `Path` class in `pathlib` represents file system paths, like `Path(\'file.txt\')`, with methods for manipulation. It’s cross-platform and intuitive for file operations.
255. What is the `subprocess` module in Python?
The `subprocess` module runs external commands, like `subprocess.run([\'ls\', \'-l\'])`, capturing output or errors. It’s used for shell interactions or process management.
256. What is the `platform` module in Python?
The `platform` module provides system information, like `platform.system()` for OS or `platform.python_version()`. It’s used for cross-platform compatibility checks.
257. What is the `sysconfig` module in Python?
The `sysconfig` module provides Python installation details, like paths or compiler flags, via `sysconfig.get_paths()`. It’s used for build tools or configuration.
258. What is the `errno` module in Python?
The `errno` module defines error codes for system calls, like `errno.ENOENT` for “no such file”. It’s used with `OSError` for error handling.
259. What is the `ctypes` module in Python?
The `ctypes` module calls C functions from shared libraries, like `ctypes.cdll.LoadLibrary()`. It’s used for low-level system integration or performance-critical code.
260. What is the `mmap` module in Python?
The `mmap` module maps files into memory, enabling efficient access or modification, like `mmap.mmap(file.fileno())`. It’s used for large file processing.
261. What is the `select` module in Python?
The `select` module monitors I/O streams, like sockets or files, for readiness, using `select.select()`. It’s used for non-blocking I/O in network applications.
262. What is the `selectors` module in Python?
The `selectors` module abstracts I/O multiplexing, improving on `select`, with classes like `DefaultSelector`. It’s used for scalable network servers.
263. What is the `asyncio` module’s `SelectorEventLoop`?
`SelectorEventLoop` is an `asyncio` event loop using `selectors` for I/O multiplexing, handling sockets or files. It’s the default loop on Unix systems.
264. What is the `queue` module in Python?
The `queue` module provides thread-safe queues, like `Queue` or `PriorityQueue`, for producer-consumer patterns. It’s used in multi-threaded applications.
265. What is the `multiprocessing.Queue` in Python?
`multiprocessing.Queue` is a process-safe queue for sharing data between processes, unlike `queue.Queue`. It’s used for inter-process communication in parallel tasks.
266. What is the `sched` module in Python?
The `sched` module implements a simple event scheduler, running tasks at specified times, like `scheduler.run()`. It’s used for basic task scheduling.
267. What is the `calendar` module in Python?
The `calendar` module provides calendar-related functions, like `calendar.month()` for printing months or `calendar.isleap()` for leap years. It’s used for date calculations.
268. What is the `locale` module in Python?
The `locale` module formats numbers, dates, or currencies based on regional settings, like `locale.setlocale()`. It’s used for internationalization in applications.
269. What is the `gettext` module in Python?
The `gettext` module supports internationalization by translating strings, using `.mo` files, like `gettext.gettext()`. It’s used for multilingual applications.
270. What is the `argparse` module’s `ArgumentParser`?
`ArgumentParser` in `argparse` defines and parses command-line arguments, with methods like `add_argument()`. It generates help messages and validates inputs.
271. What is the `optparse` module in Python?
The `optparse` module, deprecated since Python 3.2, parsed command-line options, replaced by `argparse`. It’s used in legacy code but lacks `argparse`’s flexibility.
272. What is the `cmd` module in Python?
The `cmd` module creates line-oriented command-line interfaces, with `Cmd` class for custom commands. It’s used for interactive shell applications.
273. What is the `shlex` module in Python?
The `shlex` module parses shell-like syntax, splitting strings like `shlex.split(\"ls -l\")`. It’s used for processing command-line inputs safely.
274. What is the `pprint` module in Python?
The `pprint` module formats complex data structures, like nested dictionaries, for readable output, using `pprint.pprint()`. It’s used for debugging or logging.
275. What is the `textwrap` module in Python?
The `textwrap` module formats text, li
Share this protal to share friends and complete unlimited tests here. You can also make friends on our protal also start mutual competition tests with your firends easily.