Top 50 Python Coding Interview Questions and Answers
| Summary: Summary: Product Owners and Product Managers both shape successful products, but their day-to-day focus can differ. While product managers typically work on product strategy, customer needs, and business goals, product owners focus more closely on backlogs, requirements, and development. Explore their roles, skills, career paths, salaries, and collaboration to help you decide which path best fits your interests and strengths. |
Can you solve a Python problem without relying on built-in functions or looking up the syntax? Coding interviews often test how well you apply Python concepts rather than how much theory you can remember. You may encounter problems involving strings, lists, data structures, algorithms, or debugging during the selection process. Practicing Python coding interview questions and answers helps you build familiarity with these problems, improve your coding logic, and explain your solutions clearly. This preparation can make it easier to approach technical rounds across different experience levels.
Python Coding Interview Questions and Answers for Freshers
For freshers, Python coding questions can feel challenging when you are unsure what kind of problems interviewers may ask. You might need to write a simple program, fix an error, work with lists and strings, or explain your approach step by step. Regular practice can help you become more comfortable with these tasks and improve your problem-solving skills. This section covers Python coding interview questions and answers for Freshers to help you prepare for common coding problems and approach your interview with confidence.
Q1. Write a Python program to check if a number is even or odd.
Sample Answer: Here is a sample of how to write a Python program to check if a number is even or odd:
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")


Q2. Write a Python function to reverse a string.
Sample Answer: This function, named reverse_string, takes a single string as input and uses Python’s slicing feature to return the string in reverse order. Slicing allows for concise manipulation of strings, making it easy to reverse them with just one line of code.
Here is a sample Python function to reverse a string.
def reverse_string(s):
return s[::-1]
Q3. How can you find the largest number in a list?
Sample Answer: To find the largest number in a list, you can define the function find_largest(numbers) to take a list as input and use the max() function to return the largest number from the list.
Here is an example of how you can do it:
def find_largest(numbers):
return max(numbers)
In this code, max(numbers) scans through the list and returns the highest value, making it an effective solution for this problem.
Q4. Write a program to calculate the factorial of a number.
Sample Answer: The factorial of a number is defined as the product of all positive integers less than or equal to that number, and it is denoted by ‘n!’. A recursive approach is an effective way to calculate the factorial, where the function calls itself with a decremented value until it reaches the base case.
Here’s how you can write a program to calculate the factorial of a number:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
The function factorial(n) checks whether n is 0 (the base case) and returns 1. Otherwise, it multiplies n by the factorial of n−1, recursively computing the result until it reaches the base case.
Q5. How do you check if a string is a palindrome?
Sample Answer: A palindrome is a word or phrase that reads the same forward and backward, ignoring spaces, punctuation, and capitalization. To check if a string is a palindrome, you can compare the original string with its reversed version. For example:
def is_palindrome(s):
return s == s[::-1]
The function ‘is_palindrome(s)’ checks if the input string s is equal to its reverse, ‘s[::-1]’. If they are the same, the function returns ‘True’, indicating that the string is a palindrome. Otherwise, it returns ‘False’.
Q6. Write a program to count the number of vowels in a given string.
Sample Answer: Vowels in the English language are ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’. You can iterate over the string and count how many of these vowels it contains. In the following example, the function ‘count_vowels(s)’ uses a generator expression to iterate through each character in the input string ‘s’, converting each character to lowercase to ensure the check is case-insensitive. The ‘sum()’ function then totals the number of vowels found.
Here’s the code:
def count_vowels(s):
return sum(1 for char in s if char.lower() in 'aeiou')
Q7. How do you remove duplicates from a list?
Sample Answer: Removing duplicates from a list is a common task in data manipulation. One efficient way to achieve this is to convert the list to a set, which automatically removes duplicates. After removing duplicates, you can convert the set back to a list if needed.
Here’s how you can implement this approach:
def remove_duplicates(lst):
return list(set(lst))
Q8. Write a program to find the common elements in two lists.
Sample Answer: Finding common elements between two lists is a frequent task in list manipulation. One efficient way is to convert both lists to sets and use the intersection operator, since sets support fast membership testing.
Here’s how you can implement this:
def common_elements(list1, list2):
return list(set(list1) & set(list2))
Q9. How do you merge two dictionaries in Python?
Sample Answer: When merging two dictionaries, if both dictionaries have the same key, the value from the second dictionary will overwrite the value from the first. Here is how you can merge two dictionaries in Python:
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = {**dict1, **dict2}
Q10. Write a program to sort a list of numbers.
Sample Answer: Sorting a list can be easily done using Python’s built-in sorted() function. For example:
def sort_numbers(numbers):
return sorted(numbers)
Q11. What’s the difference between mutable and immutable data types in Python?
Sample Answer: Mutable objects can be changed in place after creation. Their content can be updated without changing their identity (memory reference). Immutable objects cannot be altered once created; any operation that appears to modify them actually creates a new object. Lists, dictionaries, and sets are mutable, while integers, strings, tuples, and frozensets are immutable. This distinction matters especially when passing objects to functions, since mutable objects can be changed by reference while immutable ones cannot. Here’s an example of this:
list_example = [1, 2, 3]
list_example.append(4) # modifies in place, same object
print(list_example) # [1, 2, 3, 4]
string_example = "hello"
new_string = string_example + " world" # creates a new object
print(string_example is new_string) # False
Q12. Write a program to find the Fibonacci series up to n.
Sample Answer: The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding numbers. You can generate the sequence up to n terms. For example:
def fibonacci(n):
fib_series = [0, 1]
while len(fib_series) < n:
fib_series.append(fib_series[-1] + fib_series[-2])
return fib_series[:n]
Q13. Write a program to find the intersection of two sets.
Sample Answer: Set intersection finds the common elements between two sets. To find the intersection of two sets, you can write your code like this:
def intersection(set1, set2):
return set1 & set2
Q14. What are f-strings, and how do they compare to .format() and % formatting?
Sample Answer: f-strings, introduced in Python 3.6, let you embed expressions directly inside string literals using curly braces, prefixed with an f. They’re generally faster than both %-formatting and .format() since they’re evaluated at compile time rather than through repeated method calls at runtime. They also support inline expressions and formatting specifiers directly. Here is an example:
name = "Alice"
age = 30
# f-string (preferred)
print(f"{name} is {age} years old")
# .format() method
print("{} is {} years old".format(name, age))
# % formatting (legacy)
print("%s is %d years old" % (name, age))
# Inline expressions and formatting specifiers
print(f"{age * 2}")
print(f"{3.14159:.2f}")
Q15. How do you find the length of a list without using the len() function?
Sample Answer: Finding the length of a list without using the built-in ‘len()’ function is a useful exercise to understand iteration and counting in Python. You can achieve this by iterating through the list and incrementing a counter for each element encountered.
Here’s how you can approach it:
def get_length(lst):
count = 0
for _ in lst:
count += 1
return count
Pro Tip: Python developers are paid a good amount at some of the top IT companies in India. You can learn about the Python developer salary in India and explore the salary packages as you grow in career.
Q16. Write a Python program to check whether two strings are rotations of each other.
Sample Answer: The definition of rotations for two strings means that the first string can become the second string after some rotation. One of the simplest approaches in this case is to duplicate the first string and search the second within it.
def are_rotations(s1, s2):
return len(s1) == len(s2) and s2 in (s1 + s1)
Q17. Write a Python function to find duplicate elements in a list.
Sample Answer: Finding duplicate values is a common Python coding interview question. You can use a set to track elements you’ve seen and efficiently identify duplicates.
def find_duplicates(lst):
seen = set()
duplicates = set()
for item in lst:
if item in seen:
duplicates.add(item)
else:
seen.add(item)
return list(duplicates)
Pro Tip: Python developers are well paid at some of the top IT companies in India. You can learn about the Python developer salary in India and explore the salary packages as you grow in your career.
Python Programming Interview Questions and Answers for Mid-level Candidates
As a mid-level Python developer, your interview is likely to focus on how you approach real coding problems, not just whether you know the basics. Interviewers may test your understanding of data structures, functions, exception handling, APIs, and code optimization through practical tasks. A few Python coding questions may also require you to explain your logic, identify edge cases, or improve an existing solution. Practicing these scenarios can help you communicate your approach clearly and handle technical discussions with greater confidence.
Q18. Write a Python function to check if a number is prime.
Sample Answer: A prime number is defined as a number greater than 1 that has no divisors other than 1 and itself. To check whether a number is prime, you can iterate from 2 up to its square root, testing for any divisors. This method is efficient because if a number has a divisor larger than its square root, the corresponding quotient must be smaller than the square root.
Here is how you can implement the code:
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
Q19. Write a program to find the second largest number in a list.
Sample Answer: To find the second largest number, you can remove duplicates by converting the list to a set. Once you have a set of unique numbers, you can sort them in ascending order and retrieve the second-to-last element.
Here’s how you can implement the code:
def second_largest(numbers):
unique_numbers = list(set(numbers))
unique_numbers.sort()
return unique_numbers[-2] if len(unique_numbers) >= 2 else None
Q20. Write a Python function to flatten a nested list.
Sample Answer: To flatten a nested list, which is a list that may contain other lists as its elements, you can use a recursive approach. This method involves iterating through each item in the list and checking if it is itself a list. If it is, you recursively flatten that sublist; if it’s not, you simply add it to the flattened list.
Here is an example of how to write a Python function to flatten a nested list:
def flatten(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten(item))
else:
flat_list.append(item)
return flat_list
Q21. How can you implement a binary search in Python?
Sample Answer: Binary search is an efficient algorithm for finding a target in a sorted array. It repeatedly divides the search interval in half until the target is found.
Here is how to implement a binary search in Python:
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] < target:
low = mid + 1
elif arr[mid] > target:
high = mid - 1
else:
return mid
return -1
Pro Tip: Dealing with different types of Python technical interview coding questions can be made easy with our guide on the Python cheat sheet. It will help you tackle coding logic effectively.
Q22. Explain the Global Interpreter Lock (GIL) and its impact on multithreading.
Sample Answer: The GIL is a mutex in CPython that allows only one thread to execute Python bytecode at a time, even on multi-core systems. This means CPU-bound multithreaded programs don’t get true parallelism; threads still take turns. So multithreading mainly helps with I/O-bound tasks, like network calls or file operations, where threads spend time waiting rather than computing. For CPU-bound work, developers typically reach for multiprocessing instead. Each process gets its own interpreter and memory space, bypassing the GIL entirely. Worth noting: PEP 703 introduced an experimental GIL-free build of CPython, available starting in Python 3.13, though it’s not yet the default. For example:
import threading
import time
def io_task():
time.sleep(1)
print("Task complete")
threads = [threading.Thread(target=io_task) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
# Works well here because tasks spend most of their time waiting, not computing
Q23. What is the walrus operator (:=) and when would you use it?
Sample Answer: The walrus operator, introduced in Python 3.8, lets you assign a value to a variable as part of an expression rather than as a separate statement. This is especially useful when you want to avoid computing the same value twice, such as inside a while loop condition or a comprehension filter. For example:
# Without walrus operator
data = input("Enter something: ")
while data != "quit":
print(f"You said: {data}")
data = input("Enter something: ")
# With walrus operator
while (data := input("Enter something: ")) != "quit":
print(f"You said: {data}")
# Useful in list comprehensions too
results = [y for x in range(10) if (y := x * 2) > 5]
Q24. How do you use Python’s match-case statement introduced in modern Python versions?
Sample Answer: The match-case statement, introduced in Python 3.10, provides pattern-matching capabilities that make complex conditional logic more readable and maintainable. Here’s how you can use it:
def get_status(code):
match code:
case 200:
return "Success"
case 404:
return "Not Found"
case 500:
return "Server Error"
case _:
return "Unknown Status"
Q25. How do you implement a stack using a list?
Sample Answer: A stack is a data structure that follows a last-in, first-out (LIFO) principle. The last item added to the stack is the first one to be removed. You can implement a stack in Python using lists, which allow you to define basic operations such as push (to add an item), pop (to remove the most recently added item), and check if the stack is empty.
Here’s an example of how to create a stack class using a list:
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
return self.stack.pop() if not self.is_empty() else None
def is_empty(self):
return len(self.stack) == 0
Q26. How can you use dataclass in Python to simplify class creation?
Sample Answer: Python’s dataclass decorator automatically generates common methods such as __init__(), __repr__(), and __eq__(), reducing boilerplate code.
from dataclasses import dataclass
@dataclass
class Employee:
name: str
age: int
designation: str
emp = Employee("John", 28, "Developer")
Q27. How do context managers work, and how do you write a custom one?
Sample Answer: Context managers handle setup and teardown logic around a block of code. They’re most commonly used with the with statement to ensure resources like files or database connections are closed properly, even if an error occurs. You can build a custom one either as a class with __enter__ and __exit__ methods, or more concisely using the @contextmanager decorator from contextlib. Here is an example:
# Class-based context manager
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
self.file.close()
# Function-based, using contextlib
from contextlib import contextmanager
@contextmanager
def file_manager(filename, mode):
f = open(filename, mode)
try:
yield f
finally:
f.close()
Q28. Write a function to check if a given string is a valid palindrome considering only alphanumeric characters.
Sample Answer: To check if a string is a valid palindrome while ignoring non-alphanumeric characters, you can clean the string using regular expressions and then compare it with its reverse. Here is an example of how to check if a given string is a valid palindrome considering only alphanumeric characters:
import re
def is_valid_palindrome(s):
s = re.sub(r'[^a-zA-Z0-9]', '', s).lower()
return s == s[::-1]
Q29. How do you calculate the power of a number using recursion?
Sample Answer: Calculating the power of a number recursively involves multiplying the base by itself a specified number of times, which is determined by the exponent. The recursion continues until the exponent reaches zero, at which point the result is 1, as any number raised to the power of zero is defined as 1.
Here’s the code:
def power(base, exp):
if exp == 0:
return 1
return base * power(base, exp - 1)
Pro Tip: Preparing for a TCS interview? Check out these TCS Python interview questions and answers to practise role-specific questions and strengthen your preparation.
Q30. Write a Python function to find all unique triplets in a list that sum up to zero.
Sample Answer: To find triplets that sum to zero, you can sort the list and use a two-pointer approach to find combinations. Here is a sample Python function to find all unique triplets in a list that sum up to zero:
def three_sum(nums):
nums.sort()
result = []
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
left, right = i + 1, len(nums) - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total < 0:
left += 1
elif total > 0:
right -= 1
else:
result.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
return result
Pro Tip: Python developers can level up their careers by learning about full-stack web development. You can opt for our full-stack development course and get job placement assistance.
Q31. How do you find the intersection of two sorted arrays?
Sample Answer: Finding the intersection of two sorted arrays involves identifying the common elements that appear in both arrays. This can be efficiently achieved using a two-pointer technique, where you maintain pointers for each array and move them based on comparisons between elements.
Here’s the code to find the intersection of two sorted arrays:
def intersection_sorted(arr1, arr2):
result = []
i, j = 0, 0
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
i += 1
elif arr1[i] > arr2[j]:
j += 1
else:
result.append(arr1[i])
i += 1
j += 1
return result
Q32. Write a Python function to compute the Least Common Multiple (LCM) of two numbers.
Sample Answer: The least common multiple (LCM) can be computed using the greatest common divisor (GCD), which you can get from Python’s ‘math.gcd()’ function. Here is an example of how to write a Python function to compute the least common multiple (LCM) of two numbers:
from math import gcd
def lcm(a, b):
return abs(a * b) // gcd(a, b)
Q33. Write a Python function to group words that are anagrams.
Sample Answer: Grouping anagrams is a common coding interview problem. Words that share the same sorted character sequence belong to the same group.
from collections import defaultdict
def group_anagrams(words):
groups = defaultdict(list)
for word in words:
key = ''.join(sorted(word))
groups[key].append(word)
return list(groups.values())
Q34. How do you implement an LRU (Least Recently Used) Cache in Python?
Sample Answer: An LRU cache stores recently accessed items and removes the least recently used item when capacity is exceeded. Python’s OrderedDict can be used for implementation.
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.cache = OrderedDict()
self.capacity = capacity
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key, value):
self.cache[key] = value
self.cache.move_to_end(key)
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
Python Coding Interview Questions and Answers for Experienced Professionals
For experienced Python professionals, coding interviews often focus on how you design solutions, improve performance, and handle complex problems in real-world applications. You may be asked to work with advanced data structures, optimise code, troubleshoot errors, or discuss design decisions behind your implementation. Strong preparation also means being ready to explain why you chose a particular approach and how you would handle edge cases. Here are few commonly asked Python interview questions and answers for experienced professionals to help you prepare for these discussions.
Q35. Write a Python function to find the longest increasing subsequence in a list.
Sample Answer: The longest increasing subsequence (LIS) problem involves finding the length of the longest subsequence where each element is greater than the previous one. This can be solved using dynamic programming.
Here is the code for finding the longest increasing subsequence in a list:
def longest_increasing_subsequence(nums):
if not nums:
return 0
dp = [1] * len(nums)
for i in range(1, len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
Q36. How do you implement a binary tree and perform an in-order traversal?
Sample Answer: A binary tree is a hierarchical structure in which each node can have at most two children, referred to as the left and right child. In-order traversal is a depth-first traversal method that visits the left subtree, the root node, and then the right subtree recursively, resulting in the nodes being processed in ascending order for a binary search tree.
Here’s how you can implement a binary tree and perform an in-order traversal in Python:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.value = key
def in_order_traversal(root):
if root:
in_order_traversal(root.left) # visit the left subtree
print(root.value, end=' ') # visit root
in_order_traversal(root.right) # visit right subtree
Q37. Write a function to find all valid parentheses combinations for a given number of pairs.
Sample Answer: Generating all valid combinations of parentheses for a given number of pairs can be approached using backtracking. It systematically explores all possible combinations while ensuring they remain valid. In this case, valid combinations must have matching opening and closing parentheses. Here’s how you can code a function to find all valid parentheses combinations for n pairs:
def generate_parentheses(n):
def backtrack(s='', left=0, right=0):
if len(s) == 2 * n:
result.append(s)
return
if left < n:
backtrack(s + '(', left + 1, right)
if right < left:
backtrack(s + ')', left, right + 1)
result = []
backtrack()
return result
Q38. How do you implement a queue using two stacks?
Sample Answer: A queue follows a first-in, first-out (FIFO) principle, while stacks operate on a last-in, first-out (LIFO) basis. You can implement a queue using two stacks: one for handling enqueue operations and the other for managing dequeue operations. This method effectively simulates the queue’s behavior by reversing the order of elements when necessary.
Here’s how you can code a queue using two stacks in Python:
class Queue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def enqueue(self, item):
self.stack1.append(item)
def dequeue(self):
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop() if self.stack2 else None
Q39. Write a Python function to find the maximum product of two integers in a list.
Sample Answer: To find the maximum product of two integers in a list, you need to consider both the two largest numbers and the two smallest numbers (in the case of negative integers, their product can be larger). This approach ensures that you capture all potential pairs that could yield the highest product.
Here’s how you can write a Python function to find the maximum product of two integers in a given list:
def max_product(lst):
if len(lst) < 2:
return None # Not enough elements to form a product
# Sort the list to easily access the largest and smallest values
lst.sort()
# Calculate the product of the two largest and two smallest numbers
return max(lst[-1] * lst[-2], lst[0] * lst[1])
Q40. Explain multiprocessing vs. multithreading in Python, and when you’d choose one over the other.
Sample Answer: Multithreading runs multiple threads within a single process, sharing memory, but due to the GIL, only one thread executes Python bytecode at a time. This makes it a good fit for I/O-bound tasks like network requests or file reads. Multiprocessing creates separate processes, each with its own interpreter and memory space, allowing true parallel execution across CPU cores, which is better suited for CPU-bound tasks like heavy computation. The tradeoff is higher memory overhead and the need for explicit data sharing (via Queues or shared memory), since processes don’t share state by default. Here is an example of multiprocessing vs. multithreading in Python:
from multiprocessing import Pool
def square(n):
return n * n
if __name__ == "__main__":
with Pool(processes=4) as pool:
results = pool.map(square, [1, 2, 3, 4, 5])
print(results) # [1, 4, 9, 16, 25]
Q41. Write a Python function to solve the N-Queens problem.
Sample Answer: The N-Queens problem involves placing N queens on an N×N chessboard such that no two queens attack each other. This can be solved using backtracking.
Here is an example of how to write a Python function to solve the N-Queens Problem:
def solve_n_queens(n):
def backtrack(row, cols, diagonals1, diagonals2):
if row == n:
result.append(board[:])
return
for col in range(n):
if col in cols or (row - col) in diagonals1 or (row + col) in diagonals2:
continue
board[row] = col
cols.add(col)
diagonals1.add(row - col)
diagonals2.add(row + col)
backtrack(row + 1, cols, diagonals1, diagonals2)
cols.remove(col)
diagonals1.remove(row - col)
diagonals2.remove(row + col)
result = []
board = [-1] * n
backtrack(0, set(), set(), set())
return result
Q42. How can you implement Dijkstra’s algorithm for finding the shortest path in a graph?
Sample Answer: Dijkstra’s algorithm is used to find the shortest path from a starting node to all other nodes in a weighted graph. Here’s how you can implement it:
import heapq
def dijkstra(graph, start):
min_heap = [(0, start)]
distances = {node: float('inf') for node in graph}
distances[start] = 0
while min_heap:
current_distance, current_node = heapq.heappop(min_heap)
if current_distance > distances[current_node]:
continue
for neighbor, weight in graph[current_node].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(min_heap, (distance, neighbor))
return distances
Q43. How do you use asynchronous programming with asyncio in Python?
Sample Answer: Asynchronous programming allows multiple tasks to run concurrently without blocking execution. The asyncio module is widely used in modern Python applications.
import asyncio
async def fetch_data():
await asyncio.sleep(2)
return "Data Retrieved"
async def main():
result = await fetch_data()
print(result)
asyncio.run(main())
Q44. What are Python decorators, and how can you implement one?
Sample Answer: Decorators allow you to modify the behavior of functions without changing their source code. They are commonly used for logging, authentication, caching, and performance monitoring. Here’s an example of its implementation:
def logger(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@logger
def greet():
print("Hello World")
greet()
Q45. How do you use ‘functools.lru_cache’ for memoization, and when does it break down?
Sample Answer: ‘functools.lru_cache’ is a decorator that caches a function’s return values based on its input arguments, so repeated calls with the same arguments return the cached result instantly instead of recomputing it. This is especially useful for expensive recursive functions like Fibonacci calculations. It breaks down with unhashable arguments (lists, dictionaries), with mutable arguments that could produce stale results, or when unbounded cache growth becomes a memory concern; the maxsize parameter helps control that last issue.
Here’s how you can implement this:
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(30)) # Computed once per unique n, cached afterward
print(fibonacci.cache_info()) # Shows hits, misses, and cache size
Q46. How do you find all combinations of a given sum in a list?
Sample Answer: To find all combinations of numbers that sum up to a target value, you can use backtracking. Here is how you can find all combinations of a given sum in a list:
def combination_sum(candidates, target):
def backtrack(start, path, total):
if total == target:
result.append(path)
return
if total > target:
return
for i in range(start, len(candidates)):
backtrack(i, path + [candidates[i]], total + candidates[i])
result = []
backtrack(0, [], 0)
return result
Q47. Write a function to find the shortest path in a maze using BFS.
Sample Answer: To find the shortest path in a maze, use the breadth-first search (BFS) algorithm. This method explores all possible paths level by level, ensuring that the shortest path from the starting point to the endpoint is found.
Here’s how you can implement this:
from collections import deque
def shortest_path(maze, start, end):
rows, cols = len(maze), len(maze[0])
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
queue = deque([(start, 0)])
visited = set()
visited.add(start)
while queue:
(x, y), steps = queue.popleft()
if (x, y) == end:
return steps
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < rows and 0 <= ny < cols and maze[nx][ny] == 0 and (nx, ny) not in visited:
visited.add((nx, ny))
queue.append(((nx, ny), steps + 1))
return -1 # return -1 if no path is found
Q48. How do you detect a cycle in a directed graph using DFS?
Sample Answer: To detect a cycle in a directed graph, you can use depth-first search (DFS). You keep track of the nodes currently being explored, and if you visit a node that’s already in this exploration path, it means there’s a cycle. Here’s how you can implement this:
def has_cycle(graph):
def dfs(node):
if node in visiting:
return True
if node in visited:
return False
visiting.add(node)
for neighbor in graph[node]:
if dfs(neighbor):
return True
visiting.remove(node)
visited.add(node)
return False
visited, visiting = set(), set()
for vertex in graph:
if dfs(vertex):
return True
return False
Q49. Write a function to find the longest substring without repeating characters.
Sample Answer: You can use a method called the sliding window technique, which helps keep track of a range of unique characters. The window is adjusted when a repeated character is found, and you keep track of the longest length of this window to determine the longest substring without repeating characters.
Here’s how you can write the code to find that substring without repeating characters:
def length_of_longest_substring(s):
char_index = {}
max_length = start = 0
for index, char in enumerate(s):
if char in char_index and char_index[char] >= start:
start = char_index[char] + 1
char_index[char] = index
max_length = max(max_length, index - start + 1)
return max_length
Q50. How can you optimize memory usage when processing large datasets in Python?
Sample Answer: When working with large datasets, generators are preferred because they yield values one at a time instead of loading everything into memory. Here’s a code:
def read_large_file(file_path):
with open(file_path, "r") as file:
for line in file:
yield line.strip()
for line in read_large_file("data.txt"):
print(line)


Conclusion
This Python coding interview questions and answers guide covers the common coding problems and concepts asked during interviews. Strong preparation goes beyond solving questions. Focus on understanding your logic, writing clean code, handling edge cases, and explaining your approach clearly. Practise problems across different difficulty levels and review the solutions you get wrong. For experienced roles, also work on optimisation, debugging, and real-world coding scenarios. Consistent practice will help you strengthen your problem-solving skills and approach Python interviews with greater confidence.
Looking to secure a Python job role at Infosys? Check out our guide on Infosys Python interview questions and enhance your preparation.
To expand your career horizon, explore our curated collection of 45 essential TCS Python interview questions to equip yourself with the knowledge you need to stand out and succeed.
FAQs
Answer: Interviewers often ask questions based on strings, lists, dictionaries, loops, functions, sorting, searching, and basic data structures. For experienced candidates, questions may also cover optimisation, debugging, APIs, and real-world coding scenarios.
Answer: Start with Python fundamentals and practice simple coding problems regularly. Focus on understanding the logic behind each solution rather than memorizing code. Gradually move to medium-level problems involving data structures and problem-solving.
Answer: Experienced candidates should revise data structures, OOP, exception handling, decorators, generators, comprehensions, file handling, APIs, testing, and performance optimization. You should also practice explaining your design choices and handling edge cases.
Answer: Solve coding problems consistently and review the solutions after each practice session. Try writing your own solution before checking the answer, then look for ways to make your code cleaner, faster, and easier to maintain.




