1. Python Fundamentals
Q1. What is Python and what are its key features?
Answer:
Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum. Key features include:
Interpreted Language: No compilation needed, executes line by line
Dynamically Typed: No need to declare variable types
Object-Oriented: Supports classes and objects
Easy to Learn: Clean syntax and readability
Extensive Libraries: Rich standard library and third-party packages
Cross-Platform: Runs on Windows, Linux, macOS
Memory Management: Automatic garbage collection
Open Source: Free to use and distribute
Q2. Differentiate between lists and tuples in Python.
Answer:
| Lists | Tuples |
|---|---|
| Mutable (can be modified) | Immutable (cannot be modified) |
Created using square brackets [] | Created using parentheses () |
| Slower than tuples | Faster than lists |
| More memory consumption | Less memory consumption |
| Used for homogeneous data | Used for heterogeneous data |
Methods like append(), remove() | Limited methods available |
Example: list1 = [1, 2, 3] | Example: tuple1 = (1, 2, 3) |
Q3. What are Python's built-in data types?
Answer:
Numeric Types:
int,float,complexSequence Types:
list,tuple,rangeText Type:
strMapping Type:
dictSet Types:
set,frozensetBoolean Type:
boolBinary Types:
bytes,bytearray,memoryviewNone Type:
NoneType
Q4. Explain Python's memory management.
Answer:
Python uses:
Private Heap Space: All objects are stored in private heap
Garbage Collection: Automatic memory management through reference counting
When reference count reaches zero, object is deleted
Circular references handled by cyclic garbage collector
Memory Allocator: Python's memory manager handles allocation
Built-in Optimizations: String interning, small integer caching (-5 to 256)
Q5. What is PEP 8 and why is it important?
Answer:
PEP 8 is Python's official style guide that provides coding conventions for:
Naming conventions (snake_case for variables/functions, PascalCase for classes)
Indentation (4 spaces per level)
Maximum line length (79 characters)
Import ordering (standard libraries, third-party, local)
Whitespace usage
Comments and docstrings
Importance: Improves code readability, maintainability, and consistency across teams.
Q6. Explain the difference between == and is operators.
Answer:
==checks value equality (compares the values of objects)ischecks identity equality (checks if both refer to same memory location)
a = [1, 2, 3] b = [1, 2, 3] c = a print(a == b) # True (same values) print(a is b) # False (different objects) print(a is c) # True (same object)
Q7. What are Python decorators? Provide an example.
Answer:
Decorators are functions that modify the behavior of other functions without changing their source code.
def timer_decorator(func): import time def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f"Function {func.__name__} took {end-start:.2f} seconds") return result return wrapper @timer_decorator def long_running_function(): time.sleep(2) return "Done" long_running_function()
Q8. What is the Global Interpreter Lock (GIL)?
Answer:
GIL is a mutex that allows only one thread to execute Python bytecode at a time in CPython. This means:
Advantage: Simplifies memory management, thread-safe
Disadvantage: Limits true parallel execution in multi-core systems
Workarounds: Use multiprocessing instead of threading for CPU-bound tasks
Alternatives: Jython, IronPython don't have GIL
Q9. Explain list comprehension with an example.
Answer:
List comprehension provides a concise way to create lists.
# Traditional approach squares = [] for x in range(10): squares.append(x**2) # Using list comprehension squares = [x**2 for x in range(10)] # With condition even_squares = [x**2 for x in range(10) if x % 2 == 0] # Nested comprehension matrix = [[i*j for j in range(3)] for i in range(3)]
Q10. What are lambda functions? When to use them?
Answer:
Lambda functions are anonymous, single-expression functions.
# Syntax: lambda arguments: expression add = lambda x, y: x + y # Common use cases # 1. With map() numbers = [1, 2, 3, 4] squared = list(map(lambda x: x**2, numbers)) # 2. With filter() even = list(filter(lambda x: x % 2 == 0, numbers)) # 3. With sorted() students = [{'name': 'Alice', 'grade': 85}, {'name': 'Bob', 'grade': 90}] sorted_students = sorted(students, key=lambda x: x['grade'])
Use when: Function is small, used only once, or passed as argument to higher-order functions.
**Q11. What are *args and kwargs?
Answer:
*args: Accepts any number of positional arguments as tuple**kwargs: Accepts any number of keyword arguments as dictionary
def example_function(arg1, *args, **kwargs): print(f"First argument: {arg1}") print(f"Additional args: {args}") print(f"Keyword args: {kwargs}") example_function(1, 2, 3, 4, name="John", age=25)
Q12. Explain shallow copy vs deep copy.
Answer:
import copy original = [[1, 2], [3, 4]] # Shallow copy - Only copies references to nested objects shallow = copy.copy(original) shallow[0][0] = 99 # Affects original print(original) # [[99, 2], [3, 4]] # Deep copy - Creates new copies of all nested objects deep = copy.deepcopy(original) deep[0][0] = 100 # Doesn't affect original print(original) # [[99, 2], [3, 4]]
Q13. What is the difference between __str__ and __repr__?
Answer:
__str__: For readable, informal string representation (for end users)__repr__: For unambiguous, official string representation (for developers)
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"{self.name}, {self.age} years old" def __repr__(self): return f"Person('{self.name}', {self.age})" p = Person("Alice", 25) print(str(p)) # Alice, 25 years old print(repr(p)) # Person('Alice', 25)
Q14. How does Python handle multiple inheritance?
Answer:
Python uses Method Resolution Order (MRO) following C3 linearization algorithm.
class A: def method(self): print("A") class B(A): def method(self): print("B") class C(A): def method(self): print("C") class D(B, C): pass d = D() d.method() # Output: B (follows MRO: D -> B -> C -> A) print(D.__mro__) # Shows method resolution order
Q15. What are Python generators?
Answer:
Generators are functions that return an iterator using yield keyword.
def fibonacci_generator(n): a, b = 0, 1 count = 0 while count < n: yield a a, b = b, a + b count += 1 # Usage for num in fibonacci_generator(10): print(num) # Memory efficient - generates values on the fly
2. Data Structures
Q16. Explain Python dictionaries and their operations.
Answer:
Dictionaries are unordered collections of key-value pairs.
# Creation student = {'name': 'John', 'age': 21, 'grade': 'A'} # Access print(student['name']) # John print(student.get('age', 'Not found')) # Safe access # Operations student['age'] = 22 # Update student['city'] = 'NYC' # Add del student['grade'] # Delete # Methods keys = student.keys() values = student.values() items = student.items() # Dictionary comprehension squares = {x: x**2 for x in range(5)}
Q17. What are Python sets and their use cases?
Answer:
Sets are unordered collections of unique elements.
# Creation fruits = {'apple', 'banana', 'orange'} # Operations fruits.add('grape') fruits.remove('apple') # Set operations set1 = {1, 2, 3} set2 = {3, 4, 5} union = set1 | set2 # {1, 2, 3, 4, 5} intersection = set1 & set2 # {3} difference = set1 - set2 # {1, 2} symmetric_diff = set1 ^ set2 # {1, 2, 4, 5} # Use cases: Remove duplicates, membership testing
Q18. Explain Python's collections module.
Answer:
Useful data structures beyond built-in types:
from collections import defaultdict, Counter, deque, namedtuple # 1. defaultdict - Dictionary with default values word_count = defaultdict(int) # 2. Counter - Count hashable objects words = ['apple', 'banana', 'apple'] counter = Counter(words) # 3. deque - Double-ended queue queue = deque([1, 2, 3]) queue.append(4) # Right end queue.appendleft(0) # Left end # 4. namedtuple - Tuple with named fields Point = namedtuple('Point', ['x', 'y']) p = Point(10, 20)
Q19. How to handle missing keys in dictionaries?
Answer:
Multiple approaches:
# 1. Using get() method value = my_dict.get('key', 'default') # 2. Using setdefault() value = my_dict.setdefault('key', 'default') # 3. Using defaultdict from collections import defaultdict my_dict = defaultdict(list) my_dict['key'].append('value') # 4. Using try-except try: value = my_dict['key'] except KeyError: value = 'default'
Q20. What are Python's slicing operations?
Answer:
Slicing extracts parts of sequences using [start:stop:step] syntax.
text = "Hello World" # Basic slicing print(text[0:5]) # Hello print(text[6:]) # World print(text[:5]) # Hello print(text[-5:]) # World # With step print(text[::2]) # HloWrd print(text[::-1]) # dlroW olleH (reverse) # For lists numbers = [0, 1, 2, 3, 4, 5] print(numbers[1:4]) # [1, 2, 3] print(numbers[::2]) # [0, 2, 4]
Q21. Explain array vs list in Python.
Answer:
| Feature | List | Array (from array module) |
|---|---|---|
| Data Type | Can hold different types | Only same data type |
| Memory | More memory | Less memory |
| Performance | Slower for numerical ops | Faster for numerical ops |
| Operations | More built-in methods | Limited methods |
| Use Case | General purpose | Numerical computations |
import array # List my_list = [1, 2, 3, 'hello'] # Array my_array = array.array('i', [1, 2, 3]) # 'i' for integers
Q22. What is the difference between append() and extend()?
Answer:
# append() - Adds element as single item list1 = [1, 2, 3] list1.append([4, 5]) # [1, 2, 3, [4, 5]] # extend() - Adds elements individually list2 = [1, 2, 3] list2.extend([4, 5]) # [1, 2, 3, 4, 5]
Q23. How to sort dictionaries by value?
Answer:
scores = {'Alice': 85, 'Bob': 90, 'Charlie': 78} # Sort by value, ascending sorted_by_value = dict(sorted(scores.items(), key=lambda x: x[1])) # Sort by value, descending sorted_desc = dict(sorted(scores.items(), key=lambda x: x[1], reverse=True)) # Using itemgetter from operator import itemgetter sorted_scores = dict(sorted(scores.items(), key=itemgetter(1)))
Q24. What are Python's iterator and iterable protocols?
Answer:
Iterable: Object with
__iter__()method that returns iteratorIterator: Object with
__next__()method
class Counter: def __init__(self, low, high): self.current = low self.high = high def __iter__(self): return self def __next__(self): if self.current > self.high: raise StopIteration else: self.current += 1 return self.current - 1 for num in Counter(1, 5): print(num)
Q25. Explain the use of enumerate() and zip().
Answer:
# enumerate() - Get index and value fruits = ['apple', 'banana', 'orange'] for index, fruit in enumerate(fruits): print(f"{index}: {fruit}") # zip() - Combine multiple iterables names = ['Alice', 'Bob', 'Charlie'] ages = [25, 30, 35] for name, age in zip(names, ages): print(f"{name} is {age} years old") # Unzipping zipped = zip(names, ages) names_unzipped, ages_unzipped = zip(*zipped)
Q26. What are Python's context managers?
Answer:
Context managers handle resource management using with statement.
# Using with statement (automatic file closing) with open('file.txt', 'r') as file: content = file.read() # Creating custom context manager class Timer: def __enter__(self): import time self.start = time.time() return self def __exit__(self, exc_type, exc_val, exc_tb): import time self.end = time.time() print(f"Time taken: {self.end - self.start:.2f}s") with Timer(): # Code to time time.sleep(2)
Q27. Explain the difference between sort() and sorted().
Answer:
numbers = [3, 1, 4, 1, 5, 9] # sorted() - Returns new sorted list sorted_numbers = sorted(numbers) # New list print(numbers) # Original unchanged # sort() - Sorts list in place numbers.sort() # Original list modified print(numbers) # Sorted # Both accept key and reverse parameters sorted_numbers = sorted(numbers, reverse=True) numbers.sort(key=lambda x: str(x)) # Sort by string representation
3. Object-Oriented Programming
Q28. What are the four pillars of OOP?
Answer:
Encapsulation: Bundling data and methods, hiding internal details
Abstraction: Hiding complex implementation, showing essential features
Inheritance: Creating new classes from existing ones
Polymorphism: Same interface, different implementations
Q29. Explain Python's access modifiers.
Answer:
Python doesn't have true private/protected, but uses naming conventions:
Public: No underscore (
name)Protected: Single underscore (
_name) - convention onlyPrivate: Double underscore (
__name) - name mangling
class Student: def __init__(self): self.public = "Public" # Accessible anywhere self._protected = "Protect" # Convention only self.__private = "Private" # Name mangled to _Student__private
Q30. What is method overloading vs method overriding?
Answer:
Overloading (not directly supported in Python):
Multiple methods with same name, different parameters
Simulated using default arguments or
*args
Overriding:
Child class provides specific implementation of parent's method
class Parent: def show(self): print("Parent method") class Child(Parent): def show(self): # Overriding print("Child method")
Q31. What is the difference between abstract class and interface?
Answer:
| Abstract Class | Interface |
|---|---|
| Can have implementation | Only method signatures |
| Can have constructor | No constructor |
| Supports instance variables | Only constants |
| Use when classes are related | Use when classes share behavior |
Python: abc module | Python: Not explicitly supported |
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass def description(self): return "This is a shape"
Q32. What are class methods and static methods?
Answer:
class MyClass: class_var = "Class Variable" def __init__(self, value): self.instance_var = value @classmethod def class_method(cls): return f"Accessing {cls.class_var}" @staticmethod def static_method(): return "No access to class or instance" def instance_method(self): return f"Accessing {self.instance_var}"
Q33. Explain Python's property decorator.
Answer:
Property decorator creates getter, setter, deleter methods.
class Circle: def __init__(self, radius): self._radius = radius @property def radius(self): # Getter return self._radius @radius.setter def radius(self, value): # Setter if value < 0: raise ValueError("Radius cannot be negative") self._radius = value @property def area(self): # Read-only property return 3.14 * self._radius ** 2 circle = Circle(5) circle.radius = 10 # Uses setter print(circle.area) # Uses getter
Q34. What is multiple inheritance and its challenges?
Answer:
Multiple inheritance: Class inherits from multiple parent classes.
Challenges:
Diamond problem (ambiguous method resolution)
Complexity increases
Hard to maintain
Solution: Python uses MRO (Method Resolution Order)
class A: def method(self): print("A") class B(A): def method(self): print("B") class C(A): def method(self): print("C") class D(B, C): pass d = D() d.method() # Uses B's method (MRO: D -> B -> C -> A)
Q35. What is composition vs inheritance?
Answer:
Inheritance: "is-a" relationship
Composition: "has-a" relationship
# Inheritance class Vehicle: pass class Car(Vehicle): # Car IS-A Vehicle pass # Composition class Engine: pass class Car: def __init__(self): self.engine = Engine() # Car HAS-A Engine
Prefer composition over inheritance for flexibility.
Q36. What are magic/dunder methods?
Answer:
Special methods with double underscores for operator overloading.
class Vector: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): # Overload + return Vector(self.x + other.x, self.y + other.y) def __str__(self): # String representation return f"Vector({self.x}, {self.y})" def __len__(self): # Overload len() return 2 def __getitem__(self, index): # Overload [] if index == 0: return self.x if index == 1: return self.y raise IndexError
Q37. What is data hiding in Python?
Answer:
Data hiding restricts direct access to class members.
class BankAccount: def __init__(self, balance): self.__balance = balance # Private variable def deposit(self, amount): if amount > 0: self.__balance += amount def get_balance(self): # Controlled access return self.__balance account = BankAccount(1000) # account.__balance # Error: AttributeError print(account.get_balance()) # Correct way
4. Functions & Modules
Q38. What are Python's scoping rules?
Answer:
Python follows LEGB rule for name resolution:
Local: Inside current function
Enclosing: In enclosing functions (nested functions)
Global: At module level
Built-in: Python's built-in names
x = "global" def outer(): x = "enclosing" def inner(): x = "local" print(x) # local inner() print(x) # enclosing outer() print(x) # global
Q39. Explain Python's module and package system.
Answer:
Module: Single
.pyfile containing Python codePackage: Directory containing
__init__.pyfile and modulesLibrary: Collection of packages
# Import methods import math # Import entire module from math import sqrt # Import specific function import math as m # Import with alias from math import * # Import all (not recommended) # Package structure # mypackage/ # __init__.py # module1.py # module2.py # subpackage/ # __init__.py # module3.py
Q40. What is if __name__ == "__main__":?
Answer:
Checks if module is run directly or imported.
# mymodule.py def hello(): print("Hello from module") if __name__ == "__main__": # Executes only when run directly print("Module run directly") hello() else: print("Module imported")
Q41. What are Python's built-in functions you frequently use?
Answer:
Common built-in functions:
len(),type(),isinstance()str(),int(),float(),bool()range(),enumerate(),zip()map(),filter(),reduce()sorted(),min(),max(),sum()abs(),round(),pow()input(),print(),open()dir(),help(),id()
Q42. How to handle exceptions in Python?
Answer:
try: result = 10 / 0 file = open("nonexistent.txt") except ZeroDivisionError: print("Cannot divide by zero") except FileNotFoundError as e: print(f"File not found: {e}") except Exception as e: # Catch-all print(f"Error occurred: {e}") else: print("No exceptions occurred") finally: print("This always executes") # Raising exceptions def validate_age(age): if age < 0: raise ValueError("Age cannot be negative")
Q43. What are Python's closure functions?
Answer:
Closure is a nested function that remembers values in enclosing scope.
def outer_function(x): def inner_function(y): return x + y # Remembers x from outer scope return inner_function adder = outer_function(10) print(adder(5)) # 15 (remembers x=10)
Q44. Explain Python's functools module.
Answer:
Provides higher-order functions and operations on callable objects.
from functools import lru_cache, partial, reduce # 1. lru_cache - Memoization @lru_cache(maxsize=128) def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2) # 2. partial - Fix certain arguments def power(base, exponent): return base ** exponent square = partial(power, exponent=2) print(square(5)) # 25 # 3. reduce - Cumulative operation numbers = [1, 2, 3, 4] product = reduce(lambda x, y: x * y, numbers) # 24
Q45. What is the difference between __init__ and __new__?
Answer:
__new__: Static method, creates and returns new instance__init__: Instance method, initializes newly created object
class Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance def __init__(self): print("Initializing...") s1 = Singleton() s2 = Singleton() print(s1 is s2) # True (same instance)
5. Advanced Concepts
Q46. Explain Python's asyncio framework.
Answer:
Asyncio is for writing concurrent code using async/await syntax.
import asyncio async def fetch_data(url): print(f"Fetching {url}") await asyncio.sleep(2) # Simulate I/O operation return f"Data from {url}" async def main(): # Run concurrently tasks = [ fetch_data("url1.com"), fetch_data("url2.com"), fetch_data("url3.com") ] results = await asyncio.gather(*tasks) print(results) # Run asyncio.run(main())
Q47. What are Python's type hints?
Answer:
Type hints improve code clarity and enable static type checking.
from typing import List, Dict, Optional, Union, Tuple def process_data( data: List[int], settings: Optional[Dict[str, str]] = None ) -> Tuple[bool, str]: if settings is None: settings = {} # Function logic return True, "Success" # Union types def handle_input(value: Union[int, str]) -> None: pass # Type aliases Vector = List[float] Matrix = List[Vector]
Q48. Explain Python's metaclasses.
Answer:
Metaclasses are classes of classes that control class creation.
class SingletonMeta(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super().__call__(*args, **kwargs) return cls._instances[cls] class SingletonClass(metaclass=SingletonMeta): def __init__(self, value): self.value = value a = SingletonClass(10) b = SingletonClass(20) print(a is b) # True (same instance) print(a.value) # 10 (initial value preserved)
Q49. What is Python's multiprocessing vs threading?
Answer:
| Aspect | Threading | Multiprocessing |
|---|---|---|
| Memory | Shared memory | Separate memory |
| GIL | Affected by GIL | Bypasses GIL |
| Use Case | I/O-bound tasks | CPU-bound tasks |
| Creation Cost | Low | High |
| Communication | Queue, shared memory | Pipe, Queue |
import threading import multiprocessing import time # Threading example def worker_thread(): time.sleep(1) print("Thread done") # Multiprocessing example def worker_process(): time.sleep(1) print("Process done")
Q50. How to optimize Python code?
Answer:
Optimization techniques:
Use built-in functions (written in C)
List comprehensions over loops
Local variables access faster than global
Join strings with
join()not+Use
inoperator for membership testingProfile code with
cProfileUse
arrayornumpyfor numerical dataMemoization for repetitive calculations
Generators for memory efficiency
PyPy for JIT compilation
Q51. What are Python's memory views?
Answer:
Memory views allow accessing internal data of objects without copying.
# Create memory view data = bytearray(b'Hello World') view = memoryview(data) # Slice without copying slice_view = view[6:11] print(bytes(slice_view)) # b'World' # Modify through view view[0] = 72 # ASCII for 'H' print(data) # bytearray(b'Hello World')
Q52. Explain Python's descriptor protocol.
Answer:
Descriptors control attribute access through __get__, __set__, __delete__.
class PositiveNumber: def __init__(self, name): self.name = name def __get__(self, obj, objtype=None): return obj.__dict__.get(self.name) def __set__(self, obj, value): if value < 0: raise ValueError("Must be positive") obj.__dict__[self.name] = value class BankAccount: balance = PositiveNumber('balance') def __init__(self, balance): self.balance = balance account = BankAccount(100) account.balance = -50 # Raises ValueError
Q53. What are Python's weak references?
Answer:
Weak references don't prevent garbage collection of objects.
import weakref class Data: def __init__(self, value): self.value = value obj = Data(10) weak_ref = weakref.ref(obj) print(weak_ref()) # <__main__.Data object> del obj print(weak_ref()) # None (object was garbage collected)
Q54. Explain Python's garbage collection.
Answer:
Python uses:
Reference Counting: Each object has count of references
Cyclic Garbage Collector: Detects reference cycles
Generational GC: Objects in three generations based on age
import gc # Manual control gc.disable() gc.enable() # Get statistics print(gc.get_count()) print(gc.get_threshold()) # Force collection collected = gc.collect() print(f"Collected {collected} objects")
Q55. What are Python's slots?
Answer:__slots__ optimizes memory by predefining instance attributes.
class RegularClass: def __init__(self, x, y): self.x = x self.y = y class SlotsClass: __slots__ = ['x', 'y'] def __init__(self, x, y): self.x = x self.y = y # SlotsClass uses less memory but: # - Cannot add new attributes # - No __dict__ created
6. Practical Coding Problems
Q56. Write a function to reverse a string.
Answer:
def reverse_string(s: str) -> str: # Method 1: Slicing return s[::-1] # Method 2: Using reversed return ''.join(reversed(s)) # Method 3: Manual result = '' for char in s: result = char + result return result
Q57. Check if a string is a palindrome.
Answer:
def is_palindrome(s: str) -> bool: # Clean string and check cleaned = ''.join(char.lower() for char in s if char.isalnum()) return cleaned == cleaned[::-1] # Test cases print(is_palindrome("A man, a plan, a canal: Panama")) # True print(is_palindrome("race a car")) # False
Q58. Find the second largest number in a list.
Answer:
def second_largest(numbers: list) -> int: if len(numbers) < 2: return None first = second = float('-inf') for num in numbers: if num > first: second = first first = num elif first > num > second: second = num return second if second != float('-inf') else None # Alternative def second_largest_simple(numbers): unique = list(set(numbers)) if len(unique) < 2: return None return sorted(unique)[-2]
Q59. Implement a Fibonacci sequence generator.
Answer:
def fibonacci(n: int): # Method 1: Simple recursion (inefficient) if n <= 1: return n return fibonacci(n-1) + fibonacci(n-2) # Method 2: Dynamic programming fib = [0, 1] for i in range(2, n+1): fib.append(fib[i-1] + fib[i-2]) return fib[n] # Method 3: Space optimized a, b = 0, 1 for _ in range(n): a, b = b, a + b return a
Q60. Count frequency of words in a string.
Answer:
def word_frequency(text: str) -> dict: from collections import Counter import re # Clean and split words = re.findall(r'\b\w+\b', text.lower()) return dict(Counter(words)) # Manual implementation def word_frequency_manual(text): words = text.lower().split() freq = {} for word in words: # Remove punctuation word = word.strip('.,!?;:"') freq[word] = freq.get(word, 0) + 1 return freq
Q61. Find pairs with given sum in array.
Answer:
def find_pairs(nums: list, target: int) -> list: seen = set() pairs = [] for num in nums: complement = target - num if complement in seen: pairs.append((complement, num)) seen.add(num) return pairs # Example print(find_pairs([1, 2, 3, 4, 5], 6)) # [(2, 4), (1, 5)]
Q62. Implement a stack using Python lists.
Answer:
class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if not self.is_empty(): return self.items.pop() raise IndexError("Pop from empty stack") def peek(self): if not self.is_empty(): return self.items[-1] return None def is_empty(self): return len(self.items) == 0 def size(self): return len(self.items)
Q63. Check if two strings are anagrams.
Answer:
def are_anagrams(str1: str, str2: str) -> bool: # Method 1: Sort and compare return sorted(str1.lower()) == sorted(str2.lower()) # Method 2: Using Counter from collections import Counter return Counter(str1.lower()) == Counter(str2.lower()) # Method 3: Manual count if len(str1) != len(str2): return False count = [0] * 26 for char in str1.lower(): if char.isalpha(): count[ord(char) - ord('a')] += 1 for char in str2.lower(): if char.isalpha(): count[ord(char) - ord('a')] -= 1 return all(c == 0 for c in count)
Q64. Find the longest common prefix.
Answer:
def longest_common_prefix(strs: list) -> str: if not strs: return "" # Method 1: Horizontal scanning prefix = strs[0] for string in strs[1:]: while not string.startswith(prefix): prefix = prefix[:-1] if not prefix: return "" return prefix # Method 2: Vertical scanning for i, char in enumerate(strs[0]): for string in strs[1:]: if i >= len(string) or string[i] != char: return strs[0][:i] return strs[0]
Q65. Merge two sorted lists.
Answer:
def merge_sorted_lists(list1: list, list2: list) -> list: # Method 1: Using heapq import heapq return list(heapq.merge(list1, list2)) # Method 2: Manual merge result = [] i = j = 0 while i < len(list1) and j < len(list2): if list1[i] <= list2[j]: result.append(list1[i]) i += 1 else: result.append(list2[j]) j += 1 # Add remaining elements result.extend(list1[i:]) result.extend(list2[j:]) return result
7. Bonus Questions (2026 Focus)
Q66. What's new in Python 3.12/3.13?
Answer:
Python 3.12 features:
Improved error messages
Performance improvements
New typing features
Enhanced f-strings
Better asyncio
Python 3.13 (expected):
Subinterpreters (PEP 684)
JIT compiler improvements
Enhanced pattern matching
Better parallelism support
Q67. How to work with REST APIs in Python?
Answer:
import requests # GET request response = requests.get('https://api.example.com/data') data = response.json() # POST request payload = {'key': 'value'} response = requests.post('https://api.example.com/data', json=payload) # With authentication headers = {'Authorization': 'Bearer token'} response = requests.get(url, headers=headers) # Error handling try: response.raise_for_status() except requests.exceptions.HTTPError as e: print(f"Error: {e}")
Q68. What are Python's popular web frameworks?
Answer:
Django: Full-stack, batteries-included
Flask: Microframework, lightweight
FastAPI: Modern, async, for APIs
Pyramid: Flexible, scalable
Tornado: Async, for real-time apps
Q69. How to connect Python to databases?
Answer:
# SQLite (built-in) import sqlite3 conn = sqlite3.connect('database.db') cursor = conn.cursor() cursor.execute('SELECT * FROM users') conn.close() # PostgreSQL (psycopg2) import psycopg2 conn = psycopg2.connect( host="localhost", database="mydb", user="user", password="pass" ) # MySQL (mysql-connector) import mysql.connector conn = mysql.connector.connect( host="localhost", user="root", password="password", database="mydb" )
Q70. What are Python's testing frameworks?
Answer:
unittest: Built-in, xUnit style
pytest: Most popular, feature-rich
doctest: Tests in docstrings
nose2: Extension of unittest
hypothesis: Property-based testing
Interview Preparation Tips
1. Technical Preparation
Practice coding problems on LeetCode, HackerRank
Understand time and space complexity
Review Python's standard library
Study design patterns in Python
2. Common Mistakes to Avoid
Not understanding time complexity
Ignoring edge cases
Poor error handling
Not following PEP 8
Not asking clarifying questions
3. Behavioral Questions
Explain your projects clearly
Discuss challenges faced and solutions
Show enthusiasm for learning
Be honest about what you don't know
4. Questions to Ask Interviewer
What's the team structure like?
What projects will I work on?
What's the tech stack?
How is code reviewed?
What learning opportunities are available?
Additional Resources
Books
"Fluent Python" by Luciano Ramalho
"Python Crash Course" by Eric Matthes
"Effective Python" by Brett Slatkin
"Python Cookbook" by David Beazley
Online Courses
Python for Everybody (Coursera)
MIT OpenCourseWare - Introduction to CS with Python
Real Python tutorials
Corey Schafer's YouTube channel
Practice Platforms
LeetCode
HackerRank
Codewars
Exercism
Important Libraries to Know
Data Science: NumPy, pandas, matplotlib
Web Development: Django, Flask, FastAPI
Automation: requests, BeautifulSoup, Selenium
Testing: pytest, unittest, mock
Conclusion
This comprehensive guide covers 70+ Python interview questions ranging from fundamentals to advanced concepts. Remember:
Practice regularly - Coding is a skill that improves with practice
Understand concepts deeply - Don't just memorize answers
Build projects - Practical experience is invaluable
Stay updated - Python evolves rapidly
Communicate clearly - Explain your thought process during interviews
For 2026 interviews, focus on:
Async programming
Type hints and static typing
Modern Python features
Performance optimization
Security best practices
Good luck with your interviews! Remember that interview success comes from consistent preparation and a genuine passion for programming.