Python

Q21: How do you create a thread in Python?

Answer:
Threads in Python are created using the threading module.

Example:

 
import threading

def display():
    print("Hello Thread")

t = threading.Thread(target=display)
t.start()
 

Threads are useful for I/O-bound tasks such as file handling, networking, and API calls.


Q22: What is the difference between a Thread and a Process?

ThreadProcess
LightweightHeavyweight
Shares memorySeparate memory
Faster executionSlower than threads
Suitable for I/O tasksSuitable for CPU-intensive tasks
Created using threadingCreated using multiprocessing

Q23: How do you handle JSON data in Python?

Answer:
Python provides the json module for working with JSON data.

Common methods:

  • json.dumps() → Converts Python object to JSON string.
  • json.loads() → Converts JSON string to Python object.
  • json.dump() → Writes JSON to a file.
  • json.load() → Reads JSON from a file.

Example:

 
import json

data = {"name":"John"}

json_string = json.dumps(data)
 

Q24: What is the purpose of the logging module?

Answer:
The logging module is used to record application events, errors, warnings, and debugging information.

Logging Levels:

  • DEBUG
  • INFO
  • WARNING
  • ERROR
  • CRITICAL

It helps monitor applications and troubleshoot issues.


Q25: Explain the async and await keywords in Python.

Answer:
async and await are used for asynchronous programming.

  • async defines a coroutine.
  • await pauses execution until an asynchronous task completes.

Example:

 
import asyncio

async def hello():
    print("Hello")

asyncio.run(hello())
 

They improve performance for I/O-bound applications.


Q26: What are Context Managers in Python?

Answer:
Context Managers automatically manage resources like files, database connections, and network sockets.

They implement:

  • __enter__()
  • __exit__()

Used with the with statement.

Example:

 
with open("file.txt") as f:
    print(f.read())
 

Q27: How do you profile and optimize Python code?

Answer:
Python provides several profiling tools:

  • cProfile
  • profile
  • timeit
  • memory_profiler

Optimization techniques:

  • Use efficient algorithms
  • Reduce unnecessary loops
  • Use generators
  • Optimize database queries
  • Use built-in functions
  • Cache repeated calculations

Q28: What is the purpose of the itertools module?

Answer:
The itertools module provides fast and memory-efficient iterator functions.

Common functions:

  • count()
  • cycle()
  • repeat()
  • permutations()
  • combinations()
  • product()
  • groupby()

It is widely used in data processing and algorithm development.


Q29: Explain the use of any() and all() functions.

Answer:

any()

Returns True if at least one element is True.

Example:

 
any([False, True, False])
 

Output:

 
True
 

all()

Returns True only if every element is True.

Example:

 
all([True, True, True])
 

Output:

 
True
 

Q30: What is the purpose of the functools module?

Answer:
The functools module provides higher-order functions.

Popular functions:

  • partial()
  • reduce()
  • wraps()
  • lru_cache()

It is mainly used for decorators, caching, and function manipulation.


Q31: How do you handle circular imports in Python?

Answer:
Circular imports occur when two modules import each other.

Solutions include:

  • Move imports inside functions.
  • Restructure the project.
  • Create a common utility module.
  • Use local imports when necessary.

Q32: What is the purpose of the ctypes module?

Answer:
The ctypes module allows Python programs to call C libraries directly.

It is used for:

  • Accessing DLL/shared libraries
  • Interacting with C functions
  • Improving performance
  • System programming

Q33: How do you handle memory leaks in Python?

Answer:
Memory leaks can be minimized by:

  • Removing unused object references
  • Avoiding circular references
  • Using weak references
  • Running the garbage collector (gc)
  • Profiling memory usage using memory_profiler

Q34: Explain the purpose of the typing module.

Answer:
The typing module provides support for type hints.

Example:

 
from typing import List

def square(nums: List[int]) -> List[int]:
    return [x*x for x in nums]
 

Benefits:

  • Better code readability
  • Easier debugging
  • IDE support
  • Static type checking

Q35: What is the purpose of the heapq module?

Answer:
The heapq module implements a priority queue (min-heap).

Common functions:

  • heappush()
  • heappop()
  • heapify()
  • nlargest()
  • nsmallest()

Used in scheduling, shortest path algorithms, and priority queues.


Q36: How do you implement the Singleton Pattern in Python?

Answer:
A Singleton ensures that only one object of a class exists.

Common implementation methods:

  • Using a metaclass
  • Using __new__()
  • Module-level variables
  • Decorators

Singletons are commonly used for:

  • Database connections
  • Logging
  • Configuration management

Q37: What is the purpose of the __slots__ attribute?

Answer:
__slots__ restricts the attributes that instances of a class can have.

Benefits:

  • Reduces memory usage
  • Improves performance
  • Prevents dynamic attribute creation

Example:

 
class Student:
    __slots__ = ['name', 'age']
 

Q38: How do you create an iterator in Python?

Answer:
An iterator is created by implementing:

  • __iter__()
  • __next__()

Example:

 
class Numbers:
    def __iter__(self):
        return self

    def __next__(self):
        raise StopIteration

Q39: Explain the purpose of the bisect module.

Answer:
The bisect module provides binary search operations on sorted lists.

Common functions:

  • bisect_left()
  • bisect_right()
  • insort()

Advantages:

  • Fast searching
  • Efficient insertion
  • Maintains sorted order

Q40: What is the purpose of the concurrent.futures module?

Answer:
The concurrent.futures module provides a high-level interface for asynchronous task execution.

It supports:

  • ThreadPoolExecutor
  • ProcessPoolExecutor

Benefits:

  • Parallel task execution
  • Improved application performance
  • Simplified multithreading and multiprocessing

Example:

from concurrent.futures import ThreadPoolExecutor

def task():
    return "Task Completed"

with ThreadPoolExecutor() as executor:
    future = executor.submit(task)
    print(future.result())