Python Interview Questions
47 questions with detailed answers
Question:
How do you reverse a string in Python? Show 3 different methods.
Answer:
1. Slicing: s[::-1]\n2. reversed(): "".join(reversed(s))\n3. Loop: result = ""; for char in s: result = char + result
Question:
What is the difference between `append()` and `extend()` methods? Show with examples.
Answer:
append() adds single element:\nlst = [1, 2]; lst.append([3, 4]); # [1, 2, [3, 4]]\n\nextend() adds multiple elements:\nlst = [1, 2]; lst.extend([3, 4]); # [1, 2, 3, 4]
Question:
Explain the use of `enumerate()` function with an example.
Answer:
enumerate() returns index-value pairs:\nfruits = ["apple", "banana", "orange"]\nfor index, fruit in enumerate(fruits):\n print(f"{index}: {fruit}")\n# Output: 0: apple, 1: banana, 2: orange\n\n# Start from different index: enumerate(fruits, start=1)
Question:
How do you read and write files in Python? Show both methods.
Answer:
# Method 1 - with statement (recommended):\nwith open("file.txt", "r") as f:\n content = f.read()\n\nwith open("file.txt", "w") as f:\n f.write("Hello World")\n\n# Method 2 - manual close:\nf = open("file.txt", "r")\ncontent = f.read()\nf.close()
Question:
Write a Python function to find the factorial of a number using recursion.
Answer:
def factorial(n):\n if n == 0 or n == 1:\n return 1\n return n * factorial(n - 1)\n\n# Usage: factorial(5) returns 120
Question:
Explain the difference between `remove()`, `pop()`, and `del` for lists with examples.
Answer:
remove(): Removes first occurrence by value. lst.remove(3)\npop(): Removes by index and returns value. lst.pop(0)\ndel: Removes by index/slice. del lst[0] or del lst[1:3]
Question:
Write a Python function to find the factorial of a number using recursion.
Answer:
def factorial(n):\n if n == 0 or n == 1:\n return 1\n return n * factorial(n - 1)\n\n# Usage: factorial(5) returns 120
Question:
Explain the difference between `remove()`, `pop()`, and `del` for lists with examples.
Answer:
remove(): Removes first occurrence by value. lst.remove(3)\npop(): Removes by index and returns value. lst.pop(0)\ndel: Removes by index/slice. del lst[0] or del lst[1:3]
Question:
What is the output of the following code?\n```python\nx = [1, 2, 3]\ny = x\ny.append(4)\nprint(x)\n```
Answer:
Output: [1, 2, 3, 4]\nBoth x and y reference the same list object. Modifying y also affects x because lists are mutable and passed by reference.
Question:
Write a Python program to check if a string is a palindrome.
Answer:
def is_palindrome(s):\n s = s.lower().replace(" ", "")\n return s == s[::-1]\n\n# Usage: is_palindrome("A man a plan a canal Panama") returns True
Question:
Explain the difference between `is` and `==` with examples.
Answer:
== compares values: [1,2] == [1,2] is True\nis compares identity: [1,2] is [1,2] is False\nFor small integers: a=5; b=5; a is b is True (cached objects)
Question:
How do you handle multiple exceptions in Python? Provide an example.
Answer:
try:\n result = 10 / int(input())\nexcept (ValueError, ZeroDivisionError) as e:\n print(f"Error: {e}")\nexcept Exception as e:\n print(f"Unexpected error: {e}")
Question:
Write a Python function to find the second largest number in a list.
Answer:
def second_largest(lst):\n unique_nums = list(set(lst))\n if len(unique_nums) < 2:\n return None\n unique_nums.sort()\n return unique_nums[-2]
Question:
Write a Python function to count word frequency in a text.
Answer:
def word_frequency(text):\n words = text.lower().split()\n freq = {}\n for word in words:\n freq[word] = freq.get(word, 0) + 1\n return freq\n\n# Or using Counter: from collections import Counter; Counter(text.split())
Question:
Write a Python function to merge two sorted lists into one sorted list.
Answer:
def merge_sorted_lists(list1, list2):\n result = []\n i = j = 0\n while i < len(list1) and j < len(list2):\n if list1[i] <= list2[j]:\n result.append(list1[i])\n i += 1\n else:\n result.append(list2[j])\n j += 1\n result.extend(list1[i:])\n result.extend(list2[j:])\n return result
Question:
Write a Python function to remove duplicates from a list while preserving order.
Answer:
def remove_duplicates(lst):\n seen = set()\n result = []\n for item in lst:\n if item not in seen:\n seen.add(item)\n result.append(item)\n return result\n\n# Or using dict: list(dict.fromkeys(lst))
Question:
How do you sort a list of dictionaries by a specific key?
Answer:
students = [{"name": "John", "age": 25}, {"name": "Jane", "age": 22}]\n\n# Sort by age:\nsorted_students = sorted(students, key=lambda x: x["age"])\n\n# Or using operator.itemgetter:\nfrom operator import itemgetter\nsorted_students = sorted(students, key=itemgetter("age"))
Question:
Write a Python function to check if two strings are anagrams.
Answer:
def are_anagrams(str1, str2):\n # Method 1: Sort characters\n return sorted(str1.lower()) == sorted(str2.lower())\n\n# Method 2: Count characters\nfrom collections import Counter\ndef are_anagrams(str1, str2):\n return Counter(str1.lower()) == Counter(str2.lower())
Question:
Explain Python's `zip()` function with practical examples.
Answer:
names = ["Alice", "Bob", "Charlie"]\nages = [25, 30, 35]\n\n# Combine lists:\nfor name, age in zip(names, ages):\n print(f"{name} is {age} years old")\n\n# Create dictionary:\npeople = dict(zip(names, ages))\n\n# Unzip: names, ages = zip(*people.items())
Question:
Explain the difference between Python 2 and Python 3.
Answer:
Key differences: print statement vs function, unicode handling, integer division, range vs xrange, exception syntax, and many library changes.
Question:
What are Python's built-in data types?
Answer:
Numeric (int, float, complex), Sequence (str, list, tuple), Set (set, frozenset), Mapping (dict), Boolean (bool), Binary (bytes, bytearray).
Question:
What is PEP 8 and why is it important?
Answer:
PEP 8 is Python's style guide that defines coding conventions for readable and consistent code. It covers naming, indentation, line length, and formatting.
Question:
What are Python modules and packages?
Answer:
Modules are Python files containing code. Packages are directories containing multiple modules with __init__.py file making them importable.
Question:
Explain exception handling in Python with example.
Answer:
Use try-except blocks. Example: try: x = 1/0 except ZeroDivisionError: print("Cannot divide by zero") finally: print("Cleanup")
Question:
Explain list comprehension with example.
Answer:
Concise way to create lists. Example: squares = [x**2 for x in range(10) if x % 2 == 0] creates list of squares of even numbers.
Question:
Explain Python's import system and how modules are loaded.
Answer:
Python searches sys.path for modules, compiles to bytecode, caches in __pycache__, and stores in sys.modules to avoid reloading.
Question:
Explain Python's `*args` and `**kwargs` with a practical example.
Answer:
def my_function(*args, **kwargs):\n print("Args:", args)\n print("Kwargs:", kwargs)\n\nmy_function(1, 2, 3, name="John", age=25)\n# Args: (1, 2, 3)\n# Kwargs: {'name': 'John', 'age': 25}
Question:
Write a Python decorator that measures execution time of a function.
Answer:
import time\ndef timer(func):\n def wrapper(*args, **kwargs):\n start = time.time()\n result = func(*args, **kwargs)\n end = time.time()\n print(f"{func.__name__} took {end-start:.4f} seconds")\n return result\n return wrapper
Question:
How do you create and use a generator function? Provide an example.
Answer:
def fibonacci_gen(n):\n a, b = 0, 1\n for _ in range(n):\n yield a\n a, b = b, a + b\n\n# Usage: for num in fibonacci_gen(5): print(num)
Question:
Explain list comprehension vs generator expression with examples.
Answer:
List comprehension: squares = [x**2 for x in range(5)] # Creates list immediately\nGenerator expression: squares = (x**2 for x in range(5)) # Creates generator object, lazy evaluation
Question:
What is the difference between shallow copy and deep copy? Show with code.
Answer:
import copy\noriginal = [[1, 2], [3, 4]]\nshallow = copy.copy(original) # or original.copy()\ndeep = copy.deepcopy(original)\n\noriginal[0][0] = 99\n# shallow[0][0] is also 99, deep[0][0] remains 1
Question:
How do you implement a simple class with getter and setter properties?
Answer:
class Person:\n def __init__(self):\n self._age = 0\n \n @property\n def age(self):\n return self._age\n \n @age.setter\n def age(self, value):\n if value < 0:\n raise ValueError("Age cannot be negative")\n self._age = value
Question:
Explain the difference between `map()`, `filter()`, and `reduce()` with examples.
Answer:
map(): Applies function to all items\nlist(map(lambda x: x**2, [1,2,3])) # [1,4,9]\n\nfilter(): Filters items based on condition\nlist(filter(lambda x: x%2==0, [1,2,3,4])) # [2,4]\n\nreduce(): Reduces to single value\nfrom functools import reduce\nreduce(lambda x,y: x+y, [1,2,3,4]) # 10
Question:
How do you implement method overloading in Python?
Answer:
Python doesn't support traditional method overloading. Use default parameters or *args:\n\ndef greet(name, greeting="Hello"):\n return f"{greeting}, {name}!"\n\n# Or use functools.singledispatch for type-based dispatch:\nfrom functools import singledispatch\n@singledispatch\ndef process(arg):\n print(f"Processing {arg}")
Question:
Explain memory management in Python.
Answer:
Python uses automatic memory management with reference counting and garbage collection for cyclic references. Memory is managed by Python Memory Manager.
Question:
Explain the concept of LEGB rule in Python.
Answer:
LEGB stands for Local, Enclosing, Global, Built-in - the order Python searches for variable names in different scopes.
Question:
What are Python decorators and how do they work?
Answer:
Functions that modify other functions. They wrap another function and can execute code before/after the wrapped function runs.
Question:
Explain the concept of generators in Python.
Answer:
Functions that return iterators using yield keyword. They generate values on-demand, saving memory for large datasets.
Question:
Explain Python's garbage collection mechanism.
Answer:
Python uses reference counting and cyclic garbage collector. When reference count reaches zero, object is deleted. Cyclic GC handles circular references.
Question:
What are Python's magic methods?
Answer:
Special methods with double underscores (dunder methods) like __init__, __str__, __len__ that define object behavior for built-in operations.
Question:
Explain the concept of closures in Python.
Answer:
Nested functions that capture and remember variables from their enclosing scope even after the outer function returns.
Question:
Explain Python's multiple inheritance and MRO.
Answer:
Python supports multiple inheritance. Method Resolution Order (MRO) determines which method is called using C3 linearization algorithm.
Question:
What are context managers in Python?
Answer:
Objects that define runtime context for executing code blocks. Implement __enter__ and __exit__ methods. Used with "with" statement.
Question:
Explain the difference between deep copy and shallow copy.
Answer:
Shallow copy creates new object but references to nested objects. Deep copy creates completely independent copy including nested objects.
Question:
Explain Python's asyncio and async/await.
Answer:
Asyncio provides asynchronous programming. async/await keywords define coroutines for concurrent execution without threading overhead.
Question:
What are metaclasses in Python?
Answer:
Classes whose instances are classes themselves. They control class creation and can modify class behavior. "Classes are objects too."
Question:
Explain Python's descriptor protocol.
Answer:
Objects that define __get__, __set__, or __delete__ methods to control attribute access. Used in properties, methods, and static/class methods.