Python Interview Questions and Answers
The Python questions freshers are asked most in campus drives and technical rounds, each with the answer and a short explanation.
Q1. Which of these is a mutable data type in Python?
- A. int
- B. tuple
- C. list
- D. str
Show answerHide answer
Answer: C. list
Lists can be changed after creation; tuples, strings and ints cannot.Q2. What is the output of type(3 / 2) in Python 3?
print(type(3 / 2))
- A. <class 'double'>
- B. <class 'decimal'>
- C. <class 'int'>
- D. <class 'float'>
Show answerHide answer
Answer: D. <class 'float'>
/ always returns a float in Python 3; // is integer (floor) division.Q3. Which keyword is used to define a function in Python?
- A. function
- B. def
- C. define
- D. fun
Show answerHide answer
Answer: B. def
Functions are defined with def name(params):Q4. What does len({1, 2, 2, 3, 3, 3}) return?
print(len({1, 2, 2, 3, 3, 3}))- A. 6
- B. 4
- C. 3
- D. Error
Show answerHide answer
Answer: C. 3
A set keeps only unique values: {1, 2, 3}.Q5. Which statement about Python tuples is true?
- A. They are always sorted
- B. They use square brackets
- C. They cannot hold mixed types
- D. They are immutable
Show answerHide answer
Answer: D. They are immutable
Tuples can't be changed after creation and are written with ( ).Q6. What is the correct way to start a single-line comment in Python?
- A. #
- B. --
- C. /*
- D. //
Show answerHide answer
Answer: A. #
Python comments start with #.Q7. What does this code print?
print([1, 2, 3] * 2)
- A. [1, 2, 3, 1, 2, 3]
- B. [2, 4, 6]
- C. Error
- D. [1, 2, 3, 2]
Show answerHide answer
Answer: A. [1, 2, 3, 1, 2, 3]
Multiplying a list repeats it.Q8. Which method adds an item to the end of a list?
- A. push()
- B. insert_end()
- C. add()
- D. append()
Show answerHide answer
Answer: D. append()
list.append(x) adds x at the end. Sets use add().Q9. What does this code print?
def f(a, b=2): return a * b print(f(3))- A. 6
- B. 120
- C. 15
- D. None
Show answerHide answer
Answer: A. 6
The default argument b=2 is used, so 3 * 2 = 6.Q10. What is the output of bool('') and bool('0')?
print(bool(''), bool('0'))- A. False True
- B. True False
- C. True True
- D. False False
Show answerHide answer
Answer: A. False True
Empty strings are falsy; any non-empty string, even '0', is truthy.Q11. Which of these creates an empty dictionary?
- A. {}
- B. set()
- C. ()
- D. []
Show answerHide answer
Answer: A. {}
{} is an empty dict; an empty set must be written set().Q12. What does the 'is' operator check?
- A. Whether two values are equal
- B. Whether two names refer to the same object
- C. The type of an object
- D. Whether a value is True
Show answerHide answer
Answer: B. Whether two names refer to the same object
is compares identity; == compares values.Q13. What does this code print?
def add(x, items=[]): items.append(x) return items print(add(1), add(2))- A. [1] [2]
- B. [1, 2] [1, 2]
- C. [1] [1, 2]
- D. [1, 2] [2]
Show answerHide answer
Answer: B. [1, 2] [1, 2]
The default list is created once and shared between calls, a classic Python trap. Use None as the default instead.Q14. What is a lambda in Python?
- A. A loop keyword
- B. A module for maths
- C. A small anonymous function written in one expression
- D. A type of exception
Show answerHide answer
Answer: C. A small anonymous function written in one expression
lambda x: x * 2 creates a function without a name.Q15. What does this code print?
def f(): try: return 1 finally: return 2 print(f())- A. 3
- B. 2
- C. 1
- D. Error
Show answerHide answer
Answer: B. 2
The return inside try runs, but finally always runs too, and a return in finally overrides it.Q16. Which built-in function returns both index and value while looping?
- A. zip()
- B. range()
- C. enumerate()
- D. items()
Show answerHide answer
Answer: C. enumerate()
for i, value in enumerate(items):Q17. What does zip([1, 2, 3], ['a', 'b']) produce when converted to a list?
print(list(zip([1, 2, 3], ['a', 'b'])))
- A. [1, 'a', 2, 'b', 3]
- B. [(1, 'a'), (2, 'b'), (3, None)]
- C. Error
- D. [(1, 'a'), (2, 'b')]
Show answerHide answer
Answer: D. [(1, 'a'), (2, 'b')]
zip stops at the shortest input.Q18. What is the purpose of __init__ in a Python class?
- A. It imports a module
- B. It makes a class abstract
- C. It deletes an object
- D. It initialises a new object's attributes
Show answerHide answer
Answer: D. It initialises a new object's attributes
__init__ runs automatically when an object is created.Q19. What does this code print?
x = 10 def change(): x = 5 change() print(x)- A. 15
- B. Error
- C. 5
- D. 10
Show answerHide answer
Answer: D. 10
The function creates its own local x; the global x stays 10.Q20. Which keyword lets a function modify a variable defined at module level?
- A. nonlocal
- B. static
- C. global
- D. extern
Show answerHide answer
Answer: C. global
global x inside the function refers to the module-level x. nonlocal is for enclosing functions.Q21. What does a generator function use instead of return to produce values one at a time?
- A. emit
- B. yield
- C. produce
- D. next
Show answerHide answer
Answer: B. yield
yield pauses the function and hands back a value; it resumes on the next request.Q22. What does this code print?
print(['a', 'b', 'c'][-2:])
- A. ['a', 'b']
- B. ['b', 'c']
- C. ['c']
- D. ['a', 'b', 'c']
Show answerHide answer
Answer: B. ['b', 'c']
Negative indexes count from the end; [-2:] takes the last two items.Q23. Which of these is NOT a valid Python variable name?
- A. 2nd_place
- B. _count
- C. studentName
- D. total2
Show answerHide answer
Answer: A. 2nd_place
Names can't start with a digit.Q24. What is the result of 2 ** 3 ** 2 in Python?
print(2 ** 3 ** 2)
- A. 12
- B. 512
- C. 36
- D. 64
Show answerHide answer
Answer: B. 512
** is right-associative: 3 ** 2 = 9 first, then 2 ** 9 = 512.Q25. Which exception is raised by int('abc')?
- A. TypeError
- B. ValueError
- C. NameError
- D. SyntaxError
Show answerHide answer
Answer: B. ValueError
The type is right (a string) but the value can't be converted.Q26. What does the with statement do when opening a file?
- A. Locks the file for other programs
- B. Reads the whole file into memory
- C. Closes the file automatically when the block ends
- D. Opens the file in write mode
Show answerHide answer
Answer: C. Closes the file automatically when the block ends
with uses a context manager so the file is closed even if an error happens.Q27. What does this code print?
d = {'a': 1, 'b': 2} d['b'] = 3 print(d)- A. Error
- B. {'a': 1, 'b': 2}
- C. {'a': 1, 'b': 2, 'b': 3}
- D. {'a': 1, 'b': 3}
Show answerHide answer
Answer: D. {'a': 1, 'b': 3}
Keys are unique: assigning to an existing key replaces its value.Q28. What is the difference between a list and a tuple?
- A. Lists can't hold strings
- B. There is no difference
- C. Tuples are faster to change
- D. Lists are mutable, tuples are immutable
Show answerHide answer
Answer: D. Lists are mutable, tuples are immutable
That immutability also makes tuples usable as dictionary keys.Q29. What does this code print?
s = 'python' print(s.upper(), s[::-1])
- A. PYTHON PYTHON
- B. PYTHON nohtyp
- C. Python python
- D. python nohtyP
Show answerHide answer
Answer: B. PYTHON nohtyp
upper() returns a new uppercase string; [::-1] reverses the original lowercase one.Q30. What does PEP 8 describe?
- A. Python's package manager
- B. The Python 3.8 release
- C. A Python web framework
- D. The style guide for Python code
Show answerHide answer
Answer: D. The style guide for Python code
PEP 8 covers naming, indentation (4 spaces), line length and other style rules.Q31. What does this code print?
count = 0 for n in [2, 5, 8, 11, 14]: if n % 2 == 0: count += 1 print(count)- A. 3
- B. 0
- C. 2
- D. 5
Show answerHide answer
Answer: A. 3
2, 8 and 14 are even, so count is 3.Q32. Which data structure would you use for fast membership checks (x in collection)?
- A. list
- B. tuple
- C. string
- D. set
Show answerHide answer
Answer: D. set
Sets (and dict keys) use hashing, so 'in' is O(1) on average; lists are O(n).Q33. Which of these is immutable?
- A. set
- B. frozenset
- C. dict
- D. list
Show answerHide answer
Answer: B. frozenset
A frozenset can't be changed after creation, so it can be a dict key.Q34. What does the // operator do?
- A. Floor division
- B. Exponent
- C. Exact division
- D. Comment
Show answerHide answer
Answer: A. Floor division
7 // 2 is 3; -7 // 2 is -4 (it rounds down).Q35. Which keyword skips the rest of the current loop iteration?
- A. break
- B. skip
- C. continue
- D. pass
Show answerHide answer
Answer: C. continue
break leaves the loop; pass does nothing.Q36. What is PEP 8?
- A. A Python version
- B. A package manager
- C. Python's style guide
- D. A testing tool
Show answerHide answer
Answer: C. Python's style guide
Naming, indentation and layout conventions.Q37. What does *args collect in a function definition?
- A. Extra positional arguments as a tuple
- B. Arguments as a list of strings
- C. Only the first argument
- D. Keyword arguments as a dict
Show answerHide answer
Answer: A. Extra positional arguments as a tuple
**kwargs collects extra keyword arguments as a dict.Q38. What is a decorator?
- A. A class variable
- B. A function that wraps another function to add behaviour
- C. A way to format strings
- D. A comment above a function
Show answerHide answer
Answer: B. A function that wraps another function to add behaviour
@decorator syntax applies it, e.g. @staticmethod.Q39. What is the difference between a list and a tuple?
- A. There is no difference
- B. Tuples are mutable; lists are not
- C. Lists can't hold strings
- D. Lists are mutable; tuples are immutable
Show answerHide answer
Answer: D. Lists are mutable; tuples are immutable
Tuples are slightly faster and can be dict keys.Q40. Which module is used for regular expressions?
- A. pattern
- B. re
- C. regex
- D. string
Show answerHide answer
Answer: B. re
re.findall, re.sub, re.match.Q41. What does if __name__ == '__main__': check?
- A. Whether the file is run directly rather than imported
- B. Whether the file has errors
- C. Whether main() exists
- D. Whether Python 3 is used
Show answerHide answer
Answer: A. Whether the file is run directly rather than imported
Code under it doesn't run on import.Q42. What is the GIL in CPython?
- A. A debugging tool
- B. A package installer
- C. A lock that lets only one thread run Python bytecode at a time
- D. A garbage collector
Show answerHide answer
Answer: C. A lock that lets only one thread run Python bytecode at a time
Use multiprocessing for CPU-bound parallelism.Q43. Which function converts '42' to the integer 42?
- A. int()
- B. str()
- C. float()
- D. chr()
Show answerHide answer
Answer: A. int()
int('42') returns 42.Q44. What does pip do?
- A. Runs Python files
- B. Creates virtual machines
- C. Installs Python packages
- D. Formats code
Show answerHide answer
Answer: C. Installs Python packages
pip install requests.Q45. What is a virtual environment (venv)?
- A. A cloud server
- B. A Python emulator
- C. An isolated set of installed packages for one project
- D. A debugger
Show answerHide answer
Answer: C. An isolated set of installed packages for one project
Keeps project dependencies separate.Q46. Which is the correct way to open a file for appending?
- A. open('f.txt', 'x')
- B. open('f.txt', 'r')
- C. open('f.txt', 'a')
- D. open('f.txt', 'w')
Show answerHide answer
Answer: C. open('f.txt', 'a')
'w' overwrites; 'a' adds to the end.Q47. Which statement raises an exception on purpose?
- A. raise
- B. throw
- C. except
- D. error
Show answerHide answer
Answer: A. raise
raise ValueError('bad input').Q48. What is self in a Python method?
- A. A keyword for global variables
- B. The class itself
- C. The object the method is called on
- D. The parent class
Show answerHide answer
Answer: C. The object the method is called on
Python passes it automatically.Q49. What does a @staticmethod not receive?
- A. Any arguments
- B. self or cls
- C. A return value
- D. A docstring
Show answerHide answer
Answer: B. self or cls
It's a plain function inside the class namespace.Q50. What is duck typing?
- A. Converting types automatically
- B. Checking types at compile time
- C. Using an object based on its methods, not its declared type
- D. A type of inheritance
Show answerHide answer
Answer: C. Using an object based on its methods, not its declared type
'If it walks like a duck and quacks like a duckā¦'Q51. What does this code print?
print([x * x for x in range(4)])
- A. [1, 4, 9, 16]
- B. [0, 2, 4, 6]
- C. [0, 1, 4, 9]
- D. [0, 1, 2, 3]
Show answerHide answer
Answer: C. [0, 1, 4, 9]
Squares of 0 to 3.Q52. What does this code print?
print('hello'[::-1])- A. olleh
- B. error
- C. h
- D. hello
Show answerHide answer
Answer: A. olleh
A step of -1 walks the string backwards.Q53. What does this code print?
print(-7 // 2)
- A. -3.5
- B. 3
- C. -4
- D. -3
Show answerHide answer
Answer: C. -4
// rounds down (towards minus infinity).Q54. What does this code print?
print(-7 % 2)
- A. -2
- B. -1
- C. 1
- D. 2
Show answerHide answer
Answer: C. 1
In Python the remainder takes the sign of the divisor: -7 % 2 is 1.Q55. What does this code print?
a = [1, 2] b = a print(a is b)
- A. True
- B. None
- C. False
- D. Error
Show answerHide answer
Answer: A. True
Both names refer to the same list object.Q56. What does this code print?
a = [1, 2] b = a b.append(3) print(a)
- A. [3]
- B. [1, 2, 3]
- C. Error
- D. [1, 2]
Show answerHide answer
Answer: B. [1, 2, 3]
b and a are the same list, so appending through b changes a.Q57. What does this code print?
a = [1, 2] b = a[:] b.append(3) print(a)
- A. [3]
- B. [1, 2, 3]
- C. [1, 2]
- D. Error
Show answerHide answer
Answer: C. [1, 2]
a[:] makes a copy, so a is unchanged.Q58. What does this code print?
print({1, 2, 3, 3})- A. [1, 2, 3, 3]
- B. {1, 2, 3, 3}
- C. Error
- D. {1, 2, 3}
Show answerHide answer
Answer: D. {1, 2, 3}
A set removes the duplicate 3.Q59. What does this code print?
print(len(max(['a', 'abc', 'ab'], key=len)))
- A. 2
- B. Error
- C. 4
- D. 3
Show answerHide answer
Answer: D. 3
max with key=len picks the longest word, 'abc'.Q60. What does this code print?
print('-'.join(['a', 'b', 'c']))- A. abc
- B. a-b-c
- C. ['a', 'b', 'c']
- D. a b c
Show answerHide answer
Answer: B. a-b-c
join puts '-' between the items.Q61. What does this code print?
print('a,b,c'.split(','))- A. ['a,b,c']
- B. ['a', 'b', 'c']
- C. a b c
- D. Error
Show answerHide answer
Answer: B. ['a', 'b', 'c']
split(',') cuts at each comma.Q62. What does this code print?
print(sum(map(int, '123')))
- A. 123
- B. 15
- C. 6
- D. Error
Show answerHide answer
Answer: C. 6
sum of the list [1, 2, 3].Q63. What does this code print?
print(list(enumerate(['a', 'b'])))
- A. [('a', 0), ('b', 1)]
- B. ['a', 'b']
- C. [(0, 'a'), (1, 'b')]
- D. [0, 1]
Show answerHide answer
Answer: C. [(0, 'a'), (1, 'b')]
enumerate pairs each item with its index.Q64. What does this code print?
print(dict(zip(['a', 'b'], [1, 2])))
- A. Error
- B. {'a': 1, 'b': 2}
- C. [('a', 1), ('b', 2)]
- D. {'a', 'b'}
Show answerHide answer
Answer: B. {'a': 1, 'b': 2}
dict(zip(keys, values)) builds a dictionary.Q65. What does this code print?
d = {'x': 5} print(d.get('y', 0))- A. Error
- B. 0
- C. 1
- D. None
Show answerHide answer
Answer: B. 0
get returns the default 0 for a missing key.Q66. What does this code print?
name = 'Priya' print(f'Hello, {name}!')- A. Error
- B. Hello, {name}!
- C. Hello, Priya!
- D. Hello, name!
Show answerHide answer
Answer: C. Hello, Priya!
f-strings evaluate expressions inside braces.Q67. What does this code print?
print(f'{3.14159:.2f}')- A. 3.14159
- B. 3
- C. 3.1
- D. 3.14
Show answerHide answer
Answer: D. 3.14
.2f rounds to two decimal places.Q68. What does this code print?
a = [3, 1, 2] b = sorted(a) print(a)
- A. [2, 1, 3]
- B. None
- C. [1, 2, 3]
- D. [3, 1, 2]
Show answerHide answer
Answer: D. [3, 1, 2]
sorted returns a new list; the original is unchanged.Q69. What does this code print?
a = [3, 1, 2] print(a.sort())
- A. None
- B. [1, 2, 3]
- C. [3, 2, 1]
- D. Error
Show answerHide answer
Answer: A. None
list.sort() sorts in place and returns None.Q70. What does this code print?
print(any([0, '', [1]]))
- A. Error
- B. 1
- C. False
- D. True
Show answerHide answer
Answer: D. True
Non-empty lists are truthy; any() is true if one element is truthy.Q71. What does this code print?
print(all([1, 2, 0]))
- A. False
- B. Error
- C. True
- D. 0
Show answerHide answer
Answer: A. False
all() needs every element to be truthy; 0 is falsy.Q72. What does this code print?
a, b = 3, 2 a, b = b, a print(a, b)
- A. 3 3
- B. 3 2
- C. 2 3
- D. 2 2
Show answerHide answer
Answer: C. 2 3
Tuple unpacking swaps without a temp variable.Q73. What does this code print?
first, *rest = [1, 2, 3, 4] print(first, rest)
- A. [1] [2, 3, 4]
- B. 1 [2, 3, 4]
- C. Error
- D. 1 2
Show answerHide answer
Answer: B. 1 [2, 3, 4]
The starred name collects the rest into a list.Q74. What does this code print?
double = lambda x: x * 2 print(double(3))
- A. 3
- B. 6
- C. Error
- D. 9
Show answerHide answer
Answer: B. 6
The lambda doubles 3.Q75. What does this code print?
print(list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4])))
- A. [1, 2, 3, 4]
- B. []
- C. [1, 3]
- D. [2, 4]
Show answerHide answer
Answer: D. [2, 4]
filter keeps the even numbers.
Practised these? Now prove it.
Take a timed mock test with new questions every attempt, earn a verified certificate at 70%+, and get noticed by employers.
Start a mock test