Top 26 Python Coding Interview Questions
Top 26 Python coding interview questions with solutions: strings, lists, dictionaries, generators, decorators and classic programs for freshers and experienced.
Strings
Q1. Reverse a string
Problem: Return a string reversed.
def reverse(s: str) -> str:
return s[::-1]
print(reverse("python")) # nohtypExplanation: A slice with step -1 walks the string backwards. It is the idiomatic and fastest way in Python.
Q2. Check for a palindrome
Problem: Return True if a string reads the same backwards, ignoring case and non-alphanumeric characters.
def is_palindrome(s: str) -> bool:
clean = [c.lower() for c in s if c.isalnum()]
return clean == clean[::-1]
print(is_palindrome("Was it a car or a cat I saw?")) # TrueExplanation: Keep only letters and digits in lowercase, then compare the list with its reverse.
Q3. Check whether two strings are anagrams
Problem: Return True if two strings contain the same letters.
from collections import Counter
def is_anagram(a: str, b: str) -> bool:
return Counter(a) == Counter(b)
print(is_anagram("listen", "silent")) # TrueExplanation: Counter counts each character, and two counters are equal when every count matches. This is O(n), better than sorting.
Q4. Count the frequency of each word
Problem: Return how often each word appears in a sentence.
from collections import Counter
def word_count(text: str) -> dict:
return dict(Counter(text.lower().split()))
print(word_count("the cat and the hat"))
# {'the': 2, 'cat': 1, 'and': 1, 'hat': 1}Explanation: Split on whitespace, lowercase the words and count them. Counter.most_common(n) also gives the top n words.
Q5. Find the first non-repeating character
Problem: Return the first character that appears only once, or None.
from collections import Counter
def first_unique(s: str):
counts = Counter(s)
return next((c for c in s if counts[c] == 1), None)
print(first_unique("aabbcdd")) # cExplanation: Count characters first, then scan the string in order. next() with a default returns None when no character qualifies.
Q6. Compress a string
Problem: Turn "aaabbc" into "a3b2c1".
from itertools import groupby
def compress(s: str) -> str:
return "".join(f"{ch}{len(list(group))}" for ch, group in groupby(s))
print(compress("aaabbc")) # a3b2c1Explanation: groupby groups consecutive equal characters, so each group's length is the run length.
Lists & Dictionaries
Q7. Remove duplicates while keeping order
Problem: Return a list's unique items in their original order.
def unique(items: list) -> list:
return list(dict.fromkeys(items))
print(unique([3, 1, 3, 2, 1])) # [3, 1, 2]Explanation: Dictionaries keep insertion order, so dict.fromkeys keeps the first occurrence of each item. set() would lose the order.
Q8. Find the second largest number
Problem: Return the second largest distinct number in a list.
def second_largest(nums: list):
first = second = float("-inf")
for n in nums:
if n > first:
first, second = n, first
elif first > n > second:
second = n
return second if second != float("-inf") else None
print(second_largest([4, 1, 9, 9, 7])) # 7Explanation: Track the top two in one pass. The chained comparison first > n > second skips duplicates of the maximum.
Q9. Flatten a nested list
Problem: Flatten [1, [2, [3, 4]], 5] into [1, 2, 3, 4, 5].
def flatten(items):
for item in items:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
print(list(flatten([1, [2, [3, 4]], 5]))) # [1, 2, 3, 4, 5]Explanation: A recursive generator yields plain values and delegates nested lists to itself with yield from, so it handles any depth lazily.
Q10. Two Sum
Problem: Return the indexes of two numbers that add up to a target.
def two_sum(nums: list, target: int) -> list:
seen = {}
for i, n in enumerate(nums):
if target - n in seen:
return [seen[target - n], i]
seen[n] = i
return []
print(two_sum([3, 2, 4], 6)) # [1, 2]Explanation: Store each value's index in a dictionary and check whether the complement was already seen. This is O(n).
Q11. Merge two dictionaries
Problem: Combine two dictionaries, letting the second win on duplicate keys.
a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
merged = a | b # Python 3.9+
# or: merged = {**a, **b}
print(merged) # {'x': 1, 'y': 3, 'z': 4}Explanation: The | operator merges dictionaries into a new one, and |= updates in place. Values from the right-hand dictionary win.
Q12. Sort a dictionary by value
Problem: Return a dictionary's items sorted by value, highest first.
scores = {"asha": 82, "ravi": 95, "meera": 78}
ranked = dict(sorted(scores.items(), key=lambda kv: kv[1], reverse=True))
print(ranked) # {'ravi': 95, 'asha': 82, 'meera': 78}Explanation: Sort the (key, value) pairs with a key function that picks the value, then rebuild a dictionary, which keeps the sorted order.
Q13. Group words that are anagrams
Problem: Group ["eat", "tea", "tan", "ate", "nat"] into lists of anagrams.
from collections import defaultdict
def group_anagrams(words: list) -> list:
groups = defaultdict(list)
for w in words:
groups["".join(sorted(w))].append(w)
return list(groups.values())
print(group_anagrams(["eat", "tea", "tan", "ate", "nat"]))
# [['eat', 'tea', 'ate'], ['tan', 'nat']]Explanation: Anagrams share the same sorted letters, so use that as the key. defaultdict(list) creates each group automatically.
Q14. Find the most common element
Problem: Return the item that appears most often in a list.
from collections import Counter
def most_common(items: list):
return Counter(items).most_common(1)[0][0]
print(most_common(["a", "b", "a", "c", "a"])) # aExplanation: most_common(1) returns a list with the top (item, count) pair, so take its first element's item.
Numbers & Classic Programs
Q15. Check whether a number is prime
Problem: Return True if n is a prime number.
def is_prime(n: int) -> bool:
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
print([x for x in range(20) if is_prime(x)]) # [2, 3, 5, 7, 11, 13, 17, 19]Explanation: A factor larger than the square root would pair with one smaller than it, so checking up to the square root is enough. This is O(√n).
Q16. Generate the Fibonacci sequence
Problem: Yield the first n Fibonacci numbers.
def fibonacci(n: int):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(list(fibonacci(8))) # [0, 1, 1, 2, 3, 5, 8, 13]Explanation: Tuple assignment updates both numbers at once without a temporary variable, and the generator produces values one at a time.
Q17. Calculate a factorial
Problem: Return n! recursively and iteratively.
from math import prod
def factorial_recursive(n: int) -> int:
return 1 if n <= 1 else n * factorial_recursive(n - 1)
def factorial(n: int) -> int:
return prod(range(2, n + 1))
print(factorial(5)) # 120Explanation: The recursive version mirrors the definition. The iterative one avoids Python's recursion limit. math.factorial is built in for real use.
Q18. FizzBuzz
Problem: Print 1 to 15, with Fizz for multiples of 3, Buzz for 5 and FizzBuzz for both.
for i in range(1, 16):
out = ("Fizz" if i % 3 == 0 else "") + ("Buzz" if i % 5 == 0 else "")
print(out or i)Explanation: Build the word from both checks, and if it is empty, or falls back to the number.
Q19. Check for an Armstrong number
Problem: Return True if a number equals the sum of its digits each raised to the number of digits, like 153.
def is_armstrong(n: int) -> bool:
digits = str(n)
power = len(digits)
return n == sum(int(d) ** power for d in digits)
print(is_armstrong(153)) # True (1 + 125 + 27)Explanation: Convert the number to a string to loop over its digits, raise each to the digit count and compare the sum.
Q20. Find the GCD and LCM
Problem: Return the greatest common divisor and least common multiple of two numbers.
def gcd(a: int, b: int) -> int:
while b:
a, b = b, a % b
return a
def lcm(a: int, b: int) -> int:
return a * b // gcd(a, b)
print(gcd(12, 18), lcm(12, 18)) # 6 36Explanation: Euclid's algorithm replaces the pair with (b, a % b) until the remainder is 0. The LCM follows from a × b = gcd × lcm.
Pythonic Features
Q21. Write a timing decorator
Problem: Create a decorator that prints how long a function takes.
import time
from functools import wraps
def timed(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = fn(*args, **kwargs)
print(f"{fn.__name__} took {time.perf_counter() - start:.4f}s")
return result
return wrapper
@timed
def work():
sum(range(1_000_000))Explanation: A decorator returns a wrapper that runs code around the original function. @wraps keeps the original name and docstring.
Q22. Write a decorator that retries
Problem: Retry a function up to n times when it raises an exception.
from functools import wraps
def retry(times: int = 3):
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return fn(*args, **kwargs)
except Exception:
if attempt == times:
raise
return wrapper
return decorator
@retry(times=5)
def flaky_call():
...Explanation: A decorator with arguments needs an extra outer function that takes them and returns the real decorator.
Q23. Write a context manager
Problem: Create a context manager that times a block of code.
import time
from contextlib import contextmanager
@contextmanager
def timer(label: str):
start = time.perf_counter()
try:
yield
finally:
print(f"{label}: {time.perf_counter() - start:.3f}s")
with timer("load"):
data = [x * 2 for x in range(100_000)]Explanation: Code before yield runs on entry and code in finally runs on exit, even if the block raises an error.
Q24. Read a large file line by line
Problem: Count lines containing "ERROR" in a log file without loading it all into memory.
def count_errors(path: str) -> int:
with open(path, encoding="utf-8") as f:
return sum(1 for line in f if "ERROR" in line)Explanation: A file object is an iterator that reads one line at a time, so memory stays flat for any file size. with closes the file automatically.
Q25. Implement a simple LRU cache
Problem: Use the built-in cache, then write your own with a fixed capacity.
from collections import OrderedDict
from functools import lru_cache
@lru_cache(maxsize=128)
def square(n):
return n * n
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.data = OrderedDict()
def get(self, key):
if key not in self.data:
return -1
self.data.move_to_end(key)
return self.data[key]
def put(self, key, value):
self.data[key] = value
self.data.move_to_end(key)
if len(self.data) > self.capacity:
self.data.popitem(last=False)Explanation: OrderedDict keeps keys in use order: move_to_end marks a key as recently used and popitem(last=False) removes the oldest. get and put run in O(1).
Q26. Write a class with properties
Problem: Create a BankAccount class whose balance cannot go negative.
class BankAccount:
def __init__(self, owner: str, balance: float = 0):
self.owner = owner
self._balance = balance
@property
def balance(self) -> float:
return self._balance
def deposit(self, amount: float) -> None:
if amount <= 0:
raise ValueError("Deposit must be positive")
self._balance += amount
def withdraw(self, amount: float) -> None:
if amount > self._balance:
raise ValueError("Insufficient funds")
self._balance -= amountExplanation: The leading underscore marks _balance as internal, and the read-only balance property exposes it. All changes go through methods that enforce the rules.