Python Interview Preparation — Full Version For Freshers
(Theory + 25+ Coding Questions with Answers & Outputs)
This PDF contains a curated list of Python interview theory questions and 25+ coding problems with clear
solutions and sample outputs. Use it for structured preparation for fresher-level Python interviews. Each
coding problem shows the code and the sample result for a test input.
Contents
1. Theory Questions
2. Coding Problems (25+)
3. Quick Tips & Common Patterns
1. Theory Questions
1. What is Python?
2. What are the key features of Python?
3. What is PEP 8?
4. Difference between Python 2 and Python 3?
5. What are mutable and immutable types? Give examples.
6. Explain list, tuple, set, and dictionary.
7. What is slicing in Python?
8. Difference between '==' and 'is'.
9. What is a list comprehension? Give an example.
10. What are generators and yield?
11. What are decorators?
12. Explain *args and **kwargs.
13. Differences between shallow and deep copy.
14. What is exception handling? Explain try/except/else/finally.
15. How to read and write files in Python?
16. What is a module and a package?
17. Explain OOP concepts: class, object, inheritance, polymorphism, encapsulation.
18. What is __init__?
19. What is the difference between @staticmethod and @classmethod?
20. What is GIL (Global Interpreter Lock)?
21. How does memory management work? (reference counting, GC)
22. How to install packages using pip?
23. How to create virtual environments and why?
24. How to debug Python code (pdb, print, IDE debuggers)?
25. What are common built-in data structures and methods used in interviews?
2. Coding Problems — Solutions & Sample Outputs
1. Factorial (iterative)
def factorial(n):
if n < 0:
raise ValueError("Negative numbers not allowed")
res = 1
for i in range(2, n+1):
res *= i
return res
# sample
print("factorial(5) =", factorial(5))
Sample Output:
factorial(5) = 120
2. Check Palindrome (string)
def is_palindrome(s):
s2 = ''.join(ch.lower() for ch in s if ch.isalnum())
return s2 == s2[::-1]
print("is_palindrome('Racecar') ->", is_palindrome("Racecar"))
print("is_palindrome('Hello') ->", is_palindrome("Hello"))
Sample Output:
is_palindrome('Racecar') -> True
is_palindrome('Hello') -> False
3. Largest of Three Numbers
def largest_of_three(a, b, c):
return max(a, b, c)
print("largest_of_three(3, 7, 5) ->", largest_of_three(3,7,5))
Sample Output:
largest_of_three(3, 7, 5) -> 7
4. Fibonacci Series (first n)
def fibonacci(n):
seq = []
a, b = 0, 1
for _ in range(n):
seq.append(a)
a, b = b, a + b
return seq
print("fibonacci(8) ->", fibonacci(8))
Sample Output:
fibonacci(8) -> [0, 1, 1, 2, 3, 5, 8, 13]
5. Count Vowels in a String
def count_vowels(s):
vowels = set("aeiouAEIOU")
return sum(1 for ch in s if ch in vowels)
print("count_vowels('Hello World') ->", count_vowels("Hello World"))
Sample Output:
count_vowels('Hello World') -> 3
6. Reverse a List
def reverse_list(lst):
return lst[::-1]
print("reverse_list([1,2,3,4]) ->", reverse_list([1,2,3,4]))
Sample Output:
reverse_list([1,2,3,4]) -> [4, 3, 2, 1]
7. Filter Even Numbers from List
def evens(lst):
return [x for x in lst if x % 2 == 0]
print("evens([1,2,3,4,5,6]) ->", evens([1,2,3,4,5,6]))
Sample Output:
evens([1,2,3,4,5,6]) -> [2, 4, 6]
8. Prime Number Check
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
print("is_prime(29) ->", is_prime(29))
print("is_prime(30) ->", is_prime(30))
Sample Output:
is_prime(29) -> True
is_prime(30) -> False
9. Bubble Sort
def bubble_sort(arr):
a = arr[:]
n = len(a)
for i in range(n):
for j in range(0, n-1-i):
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j]
return a
print("bubble_sort([5,2,9,1]) ->", bubble_sort([5,2,9,1]))
Sample Output:
bubble_sort([5,2,9,1]) -> [1, 2, 5, 9]
10. Merge Two Sorted Lists
def merge_sorted(a, b):
i = j = 0
out = []
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i]); i+=1
else:
out.append(b[j]); j+=1
out.extend(a[i:]); out.extend(b[j:])
return out
print("merge_sorted([1,3,5],[2,4,6]) ->", merge_sorted([1,3,5],[2,4,6]))
Sample Output:
merge_sorted([1,3,5],[2,4,6]) -> [1, 2, 3, 4, 5, 6]
11. Find Duplicates in a List
from collections import Counter
def find_duplicates(lst):
c = Counter(lst)
return [item for item, count in c.items() if count > 1]
print("find_duplicates([1,2,2,3,4,4,4]) ->", find_duplicates([1,2,2,3,4,4,4]))
Sample Output:
Error during execution: name 'Counter' is not defined\n
12. Anagram Check
def are_anagrams(a, b):
return sorted(a.replace(" ", "").lower()) == sorted(b.replace(" ", "").lower())
print("are_anagrams('listen','silent') ->", are_anagrams("listen","silent"))
Sample Output:
are_anagrams('listen','silent') -> True
13. Matrix Transpose
def transpose(matrix):
return [list(row) for row in zip(*matrix)]
m = [[1,2,3],[4,5,6]]
print("transpose([[1,2,3],[4,5,6]]) ->", transpose(m))
Sample Output:
transpose([[1,2,3],[4,5,6]]) -> [[1, 4], [2, 5], [3, 6]]
14. List Comprehension Example
squares = [x*x for x in range(6)]
print("squares ->", squares)
Sample Output:
squares -> [0, 1, 4, 9, 16, 25]
15. Generator Example (yield)
def gen_numbers(n):
for i in range(n):
yield i*i
print("list(gen_numbers(5)) ->", list(gen_numbers(5)))
Sample Output:
list(gen_numbers(5)) -> [0, 1, 4, 9, 16]
16. Decorator Example
def debug(fn):
def wrapper(*args, **kwargs):
print(f"Calling {fn.__name__} with", args, kwargs)
res = fn(*args, **kwargs)
print(f"{fn.__name__} returned", res)
return res
return wrapper
@debug
def add(a,b):
return a+b
print("add(3,4) ->", add(3,4))
Sample Output:
Calling add with (3, 4) {}
add returned 7
add(3,4) -> 7
17. Class & Object Example
class Person:
species = "Homo sapiens" # class variable
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hi, I'm {self.name} and I'm {self.age} years old."
p = Person("Alice", 23)
print("p.greet() ->", p.greet())
print("Person.species ->", Person.species)
Sample Output:
p.greet() -> Hi, I'm Alice and I'm 23 years old.
Person.species -> Homo sapiens
18. Lambda for Sorting
names = ["anna","bob","charlie","david"]
sorted_by_last = sorted(names, key=lambda x: x[-1])
print("sorted_by_last ->", sorted_by_last)
Sample Output:
sorted_by_last -> ['anna', 'bob', 'david', 'charlie']
19. Binary Search
def binary_search(arr, target):
lo, hi = 0, len(arr)-1
while lo <= hi:
mid = (lo+hi)//2
if arr[mid] == target:
return mid
elif arr[mid] < target:
lo = mid+1
else:
hi = mid-1
return -1
print("binary_search([1,3,5,7,9],7) ->", binary_search([1,3,5,7,9],7))
Sample Output:
binary_search([1,3,5,7,9],7) -> 3
20. Count Frequency of Elements
from collections import Counter
def freq(s):
return Counter(s)
print("freq('abracadabra') ->", freq("abracadabra"))
Sample Output:
Error during execution: name 'Counter' is not defined\n
21. Flatten Nested List
def flatten(lst):
out = []
for el in lst:
if isinstance(el, list):
out.extend(flatten(el))
else:
out.append(el)
return out
print("flatten([1,[2,3],[4,[5]]]) ->", flatten([1,[2,3],[4,[5]]]))
Sample Output:
Error during execution: name 'flatten' is not defined\n
22. Sum of Digits
def sum_digits(n):
return sum(int(d) for d in str(abs(n)))
print("sum_digits(12345) ->", sum_digits(12345))
Sample Output:
sum_digits(12345) -> 15
23. Armstrong Number Check
def is_armstrong(n):
s = str(n)
power = len(s)
return sum(int(d)**power for d in s) == n
print("is_armstrong(153) ->", is_armstrong(153))
print("is_armstrong(123) ->", is_armstrong(123))
Sample Output:
is_armstrong(153) -> True
is_armstrong(123) -> False
24. GCD and LCM
import math
def gcd(a,b): return math.gcd(a,b)
def lcm(a,b): return abs(a*b)//gcd(a,b) if a and b else 0
print("gcd(12,18) ->", gcd(12,18))
print("lcm(12,18) ->", lcm(12,18))
Sample Output:
Error during execution: name 'math' is not defined\n
25. Swap Two Variables Without Temp
def swap(a,b):
a, b = b, a
return a, b
print("swap(3,4) ->", swap(3,4))
Sample Output:
swap(3,4) -> (4, 3)
26. Merge Sort (recursive)
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr)//2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
i = j = 0
out = []
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i]); i+=1
else:
out.append(right[j]); j+=1
out.extend(left[i:]); out.extend(right[j:])
return out
print("merge_sort([5,3,8,1,2]) ->", merge_sort([5,3,8,1,2]))
Sample Output:
Error during execution: name 'merge_sort' is not defined\n
3. Quick Tips & Common Patterns
- Practice writing code by hand for basic problems (sorting, searching, string manipulation).
- Know time/space complexity of common algorithms (O(n), O(n log n), O(n^2)).
- Use Python standard library: collections, itertools, math, functools.
- Be comfortable with list comprehensions, generators, and basic OOP.
- Read error tracebacks carefully during debugging.