Skip to main content

python basic and advance 100 interview question and answer

 

1. What is Python?

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

2. What are Python’s key features?

  • Easy to learn and use
  • Interpreted language
  • Dynamically typed
  • Extensive libraries
  • Support for object-oriented programming

3. What is PEP 8?

PEP 8 is the Python Enhancement Proposal that provides guidelines and best practices on how to write Python code. It emphasizes readability and consistency.

4. How is memory managed in Python?

Memory management in Python is handled by the Python memory manager, which includes a private heap containing all Python objects and data structures. Python also has an inbuilt garbage collector that recycles all unused memory.

5. What are lists and tuples?

  • Lists are mutable, ordered collections that can contain elements of different types.
  • Tuples are immutable, ordered collections that can also contain elements of different types.

6. How do you create a list in Python?

python
my_list = [1, 2, 3, 'a', 'b']

7. What is a dictionary?

A dictionary is an unordered, mutable collection of key-value pairs. Keys must be unique and immutable.

8. How do you create a dictionary in Python?

python
my_dict = {'name': 'Alice', 'age': 25}

9. What is a set?

A set is an unordered collection of unique elements. It is mutable and can be used for membership testing and eliminating duplicate entries.

10. How do you create a set in Python?

python
my_set = {1, 2, 3}

11. What are functions in Python?

Functions are blocks of reusable code that perform a specific task. They can take inputs (arguments) and return outputs.

12. How do you define a function in Python?

python
def my_function(param1, param2): return param1 + param2

13. What is a lambda function?

A lambda function is an anonymous function expressed as a single statement. It can take any number of arguments but can only have one expression.

python
add = lambda x, y: x + y

14. What are *args and **kwargs?

  • *args allows you to pass a variable number of non-keyword arguments to a function.
  • **kwargs allows you to pass a variable number of keyword arguments.

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

  • Shallow copy creates a new object, but inserts references into it to the objects found in the original.
  • Deep copy creates a new object and recursively adds copies of nested objects found in the original.

16. What are list comprehensions?

List comprehensions provide a concise way to create lists. They consist of brackets containing an expression followed by a for clause.

python
squares = [x**2 for x in range(10)]

17. What are generators?

Generators are a type of iterable, created using a function that yields values one at a time, instead of returning them all at once.

18. What is the purpose of the yield keyword?

yield is used to produce a generator, allowing the function to return an intermediate result and resume where it left off.

19. Explain the use of the with statement.

The with statement is used for resource management and exception handling. It ensures that resources are properly managed (e.g., files are closed).

python
with open('file.txt', 'r') as file: data = file.read()

20. What is exception handling?

Exception handling in Python is a way to handle errors gracefully using tryexceptfinally, and else blocks.

21. How do you raise an exception?

You can raise an exception using the raise keyword.

python
raise ValueError("Invalid value")

22. What is the purpose of __init__.py?

__init__.py is used to mark a directory as a Python package. It can also execute initialization code for the package.

23. Explain the concept of decorators.

Decorators are a way to modify or enhance functions or methods without changing their code. They are often used for logging, access control, or instrumentation.

24. What is a class in Python?

A class is a blueprint for creating objects that encapsulate data (attributes) and behaviors (methods).

25. How do you define a class in Python?

python
class Dog: def bark(self): return "Woof!"

26. What is inheritance?

Inheritance allows a class (child class) to inherit attributes and methods from another class (parent class), promoting code reusability.

27. What is polymorphism?

Polymorphism allows methods to do different things based on the object it is acting upon, allowing for method overriding and overloading.

28. What are modules?

Modules are files containing Python code (functions, classes, variables) that can be imported and used in other Python files.

29. What is the difference between import and from ... import?

  • import module imports the whole module.
  • from module import name imports specific attributes from a module.

30. What is the Global Interpreter Lock (GIL)?

The GIL is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecode simultaneously.

31. How do you manage dependencies in Python?

Dependencies can be managed using tools like pip for package installation and requirements.txt files for listing dependencies.

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

  • == checks for value equality.
  • is checks for identity (whether two references point to the same object).

33. What are Python’s built-in data types?

  • Numeric Types: int, float, complex
  • Sequence Types: list, tuple, range
  • Text Type: str
  • Binary Types: bytes, bytearray, memoryview
  • Mapping Type: dict
  • Set Types: set, frozenset
  • Boolean Type: bool

34. What is the purpose of the pass statement?

The pass statement is a null operation that serves as a placeholder in blocks where syntactically some code is required but you do not want to execute anything.

35. How can you swap two variables in Python?

python
a, b = b, a

36. What are the differences between Python 2 and Python 3?

  • Print Function: Python 3 uses print() as a function.
  • Integer Division: Python 3 performs true division with / and floor division with //.
  • Unicode: Strings are Unicode by default in Python 3.

37. How do you read and write files in Python?

python
# Reading a file with open('file.txt', 'r') as file: data = file.read() # Writing to a file with open('file.txt', 'w') as file: file.write("Hello, World!")

38. What is the difference between str and repr?

  • str is meant for creating output for end-users.
  • repr is meant for creating output for developers, often including more detail.

39. What is the purpose of the __str__ and __repr__ methods?

  • __str__ is used to define a user-friendly string representation of an object.
  • __repr__ is used to define an unambiguous string representation of an object.

40. Explain list slicing.

List slicing allows you to access a subset of a list by specifying a start, stop, and step index.

python
my_list = [1, 2, 3, 4, 5] sub_list = my_list[1:4] # [2, 3, 4]

41. What is the purpose of the enumerate() function?

enumerate() adds a counter to an iterable and returns it as an enumerate object.

python
for index, value in enumerate(['a', 'b', 'c']): print(index, value)

42. How can you merge two dictionaries in Python 3.5+?

You can use the ** unpacking operator.

python
dict1 = {'a': 1} dict2 = {'b': 2} merged = {**dict1, **dict2}

43. What is the filter() function?

filter() constructs an iterator from elements of an iterable for which a function returns true.

even_numbers = list(filter(lambda x: x % 2 == 0, range(10)))

44. Explain the use of the map() function.

map() applies a given function to all items in an iterable.

python
squared = list(map(lambda x: x**2, range(5)))

45. What is the reduce() function?

reduce() applies a rolling computation to sequential pairs of values in an iterable, reducing it to a single value. It requires importing from functools.

python
from functools import reduce result = reduce(lambda x, y: x + y, [1, 2, 3, 4])

46. What are f-strings?

F-strings are formatted string literals in Python 3.6 and later that provide a way to embed expressions inside string literals.

python
name = "Alice" greeting = f"Hello, {name}!"

47. What are context managers?

Context managers are used to manage resources, typically with the with statement, ensuring proper acquisition and release of resources.

48. How can you sort a list in Python?

You can sort a list using the sort() method or the sorted() function.

python
my_list.sort() # In-place sort sorted_list = sorted(my_list) # Returns a new sorted list

49. What is multithreading?

Multithreading is a technique that allows concurrent execution of threads, enabling parallelism and improving performance for I/O-bound tasks.

50. What are async and await?

async and await are used for defining and handling asynchronous code, allowing for non-blocking execution of code.

51. How do you handle JSON in Python?

You can handle JSON using the json module.

python
import json data = json.loads('{"name": "Alice"}') # Deserialize json_string = json.dumps(data) # Serialize

52. What are regular expressions?

Regular expressions are sequences of characters that define search patterns, commonly used for string matching and manipulation.

53. How do you create a virtual environment?

You can create a virtual environment using the venv module.

bash
python -m venv myenv

54. What is the purpose of the requests library?

The requests library is used for making HTTP requests in Python, simplifying the process of sending and receiving data over the web.

55. How do you install a package in Python?

You can install packages using pip:

bash
pip install package_name

56. What is the difference between deepcopy and copy?

  • copy creates a shallow copy of an object.
  • deepcopy creates a deep copy, including copies of nested objects.

57. What is the __main__ block?

The __main__ block allows you to check whether a Python file is being run as a script or imported as a module.

python
if __name__ == "__main__": # code to execute

58. What is the purpose of assert?

assert is used to test if a condition in your code returns True. If it doesn’t, an AssertionError is raised.

python
assert x > 0, "x should be positive"

59. How can you reverse a string in Python?

You can reverse a string using slicing.

python
reversed_string = my_string[::-1]

60. How do you find the length of a list?

You can find the length of a list using the len() function.

python
length = len(my_list)

61. What is a breakpoint?

A breakpoint is a debugging tool that allows you to pause the execution of a program at a specified line of code for inspection.

62. What is a module and how is it different from a package?

A module is a single file containing Python code, while a package is a collection of modules in a directory with an __init__.py file.

63. How do you convert a string to an integer?

You can convert a string to an integer using the int() function.

python
number = int("123")

64. How do you check if a string contains a substring?

You can check if a string contains a substring using the in keyword.

python
if "abc" in my_string: print("Found")

65. What are global and local variables?

  • Global variables are defined outside of functions and can be accessed anywhere in the code.
  • Local variables are defined within a function and can only be accessed within that function.

66. How do you handle command-line arguments?

You can handle command-line arguments using the sys module or the argparse module for more complex parsing.

python
import sys print(sys.argv)

67. What is type hinting?

Type hinting is a feature in Python that allows you to specify the expected data types of variables and function arguments, enhancing code readability and enabling better static analysis.

68. How do you implement a stack in Python?

You can implement a stack using a list.

python
stack = [] stack.append(1) # Push item = stack.pop() # Pop

69. How do you implement a queue in Python?

You can implement a queue using collections.deque for efficient appending and popping.

python
from collections import deque queue = deque() queue.append(1) # Enqueue item = queue.popleft() # Dequeue

70. What is the difference between a function and a method?

A function is a standalone block of code, while a method is a function that is associated with an object or class.

71. What are Python decorators and how do they work?

Decorators are functions that modify the behavior of another function. They are applied using the @decorator_name syntax above the function definition.

72. Explain the use of super().

super() is used to call methods from a parent class within a child class, facilitating inheritance and code reuse.

python
class Parent: def greet(self): print("Hello from Parent") class Child(Parent): def greet(self): super().greet() # Call Parent's greet print("Hello from Child")

73. What is a property in Python?

Properties are a way to manage the attributes of a class, allowing for getter, setter, and deleter functionality without changing the attribute's direct access.

python
class MyClass: def __init__(self): self._value = 0 @property def value(self): return self._value @value.setter def value(self, new_value): self._value = new_value

74. What is the difference between isinstance() and type()?

  • isinstance() checks if an object is an instance of a class or a subclass.
  • type() returns the exact type of an object.

75. What is the use of the self keyword?

self refers to the instance of the class in which it is defined, allowing access to class attributes and methods.

76. Explain method overloading in Python.

Python does not support method overloading in the traditional sense. However, you can achieve similar behavior by using default arguments or variable-length arguments.

77. What is a class method?

A class method is a method that is bound to the class rather than its instance. It can modify class state that applies across all instances of the class.

python
class MyClass: count = 0 @classmethod def increment_count(cls): cls.count += 1

78. What is an instance method?

An instance method is a method that operates on an instance of the class, accessing instance variables.

79. What is encapsulation?

Encapsulation is the bundling of data (attributes) and methods that operate on that data within a single unit (class) and restricting access to some components.

80. How do you create a singleton class in Python?

You can create a singleton class by controlling instance creation in the __new__ method.

python
class Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super(Singleton, cls).__new__(cls) return cls._instance

81. What are __str__ and __repr__?

  • __str__: Used to provide a human-readable string representation of an object.
  • __repr__: Used to provide an unambiguous representation of an object, useful for debugging.

82. What is method resolution order (MRO)?

MRO is the order in which base classes are searched when looking for a method. Python uses the C3 linearization algorithm for MRO.

83. How do you create a custom exception?

You can create a custom exception by subclassing the built-in Exception class.

python
class MyCustomError(Exception): pass

84. What are the benefits of using Python for web development?

  • Simple syntax and readability
  • A wide range of frameworks (Django, Flask)
  • Extensive libraries for various tasks
  • Strong community support

85. How do you perform unit testing in Python?

You can perform unit testing using the unittest module.

python
import unittest class TestMyFunction(unittest.TestCase): def test_case(self): self.assertEqual(my_function(1, 2), 3)

86. What is the purpose of the assertEqual method?

assertEqual checks if two values are equal and raises an assertion error if they are not.

87. What is the use of the mock module in Python?

The mock module is used for testing by replacing parts of your system under test and making assertions about how they have been used.

88. How can you test for memory leaks in Python?

You can use tools like objgraphguppy, or memory profilers to check for memory leaks during the execution of your code.

89. What is a closure in Python?

A closure is a nested function that captures the variables from its enclosing scope, even after the outer function has finished executing.

90. What are coroutines?

Coroutines are a special type of function that can pause and resume their execution, allowing for cooperative multitasking and asynchronous programming.

91. How do you convert a list to a set?

You can convert a list to a set using the set() constructor.

python
my_set = set(my_list)

92. How can you find the maximum and minimum values in a list?

You can use the max() and min() functions.

python
maximum = max(my_list) minimum = min(my_list)

93. What is a Python wheel?

A wheel is a built package format for Python that provides a convenient way to distribute Python packages and speed up installation.

94. How do you debug a Python program?

You can debug a Python program using built-in tools like pdb, or by using IDE features or print statements to trace execution.

95. What is pickle used for?

pickle is a module used for serializing and deserializing Python object structures, allowing you to save Python objects to files.

96. How do you use the itertools module?

itertools provides functions that create iterators for efficient looping. Examples include count()cycle(), and combinations().

97. What is the csv module used for?

The csv module is used to read and write CSV files in Python, providing functionality to handle CSV data easily.

98. How do you use the random module?

The random module provides functions for generating random numbers and performing random actions.

python
import random random_number = random.randint(1, 10)

99. What is the difference between breakcontinue, and pass?

  • break exits the loop.
  • continue skips the rest of the current loop iteration and moves to the next iteration.
  • pass does nothing and serves as a placeholder.

100. What are the key differences between REST and SOAP?

  • REST is an architectural style that uses standard HTTP methods, is stateless, and typically uses JSON or XML. It's more lightweight and easier to consume.
  • SOAP is a protocol with strict standards and relies on XML. It supports more complex operations and is used in enterprise environments.