๐Ÿ  Home๐ŸŽฎ Play Game Modes๐Ÿ† Daily Challenge๐Ÿค– AI Generatorโ„น๏ธ About Us๐Ÿ“ Quiz Blog๐Ÿ“ฌ Contact Us
๐Ÿ Home
Blog
๐Ÿ“Python Quiz Guide
๐Ÿ
Programming & Technology

Python Quiz: 100 MCQ Questions for Interview Prep (2026)

Preparing for a Python technical round? Sharpen your knowledge of memory scopes, data structures, constructors, and decorators with our curated list of 100 multiple-choice questions.

Core Python Interview Concepts

Python is one of the most widely used programming languages, but its high-level abstraction often hides complex details. Core concepts such as mutable default arguments, hashing behaviors, reference cycle garbage collection, and thread locking under the Global Interpreter Lock (GIL) are frequent interview topics.

Practicing conceptual multiple-choice questions with output predictions is a highly effective way to identify and fill knowledge gaps before a coding review.

Python Scope and Variables Overview

Local Scope (L)

Variables defined inside the current function.

Enclosing Scope (E)

Variables defined in nested outer functions (nonlocal).

Global Scope (G)

Variables defined at the module-level of the script.

Built-in Scope (B)

Pre-assigned keywords and functions (e.g. print, len, range).

100 Python Interview Questions and Answers

Test your knowledge with these coding questions. Review the detailed explanations to understand the code evaluation logic.

1What is the output of: print(type([1, 2] * 0))?

Answer: <class 'list'>

๐Ÿ’ก Explanation: Multiplying a list by 0 yields an empty list []. The type of an empty list remains a list, so print(type([])) outputs <class 'list'>.

2What is the output of the following code:

def func(a, b=[]):
    b.append(a)
    return b

print(func(1))
print(func(2))

Answer: [1] and [1, 2]

๐Ÿ’ก Explanation: Default arguments in Python are evaluated once when the function is defined, not when it is called. The mutable default list `b` is shared across calls. The first call appends 1, and the second call appends 2 to the same list.

3Which of the following is used to manage resources like file streams safely in Python, even if exceptions occur?

Answer: with statement (context managers)

๐Ÿ’ก Explanation: The `with` statement utilizes context managers (implementing __enter__ and __exit__ magic methods) to guarantee cleanup operations (like closing files or database connections) are executed.

4What is the output of the following dictionary operation:

d = {1: "a", 1.0: "b"}
print(d[1])

Answer: b

๐Ÿ’ก Explanation: In Python, 1 and 1.0 hash to the exact same value, and they compare as equal (1 == 1.0). Since keys must be unique, the entry for 1.0 overrides the value for 1, resulting in d[1] returning "b".

5How does Python handle memory management under the hood?

Answer: Automatic garbage collection using reference counting and a cyclic garbage collector

๐Ÿ’ก Explanation: Python uses reference counting as its primary mechanism (deallocating objects when refcount hits 0) supplemented by a generational garbage collector to identify and clear reference cycles.

6What is the output of the following list comprehension:

nums = [1, 2, 3]
print([x * y for x in nums for y in [0, 1] if x > 1])

Answer: [0, 2, 0, 3]

๐Ÿ’ก Explanation: The outer loop filters x > 1, retaining 2 and 3. For 2, y = [0, 1] yields 0 and 2. For 3, y = [0, 1] yields 0 and 3. Combining these yields the flat list: [0, 2, 0, 3].

7What is the difference between a shallow copy and a deep copy in Python (copy module)?

Answer: Shallow copy copies references of nested objects; deep copy recursively copies values of nested objects.

๐Ÿ’ก Explanation: `copy.copy()` constructs a new compound object and inserts references to the original nested elements. `copy.deepcopy()` recursively copies nested objects, preventing changes to the copied object from affecting the original.

8What is the purpose of the __init__ method in a Python class?

Answer: It acts as a constructor to initialize instance attributes when an object is instantiated.

๐Ÿ’ก Explanation: `__init__` is an instance initializer called automatically after the object is created by `__new__` to bind initial state variables to the `self` object.

9What is the output of the following generator expression:

gen = (x for x in range(3))
print(list(gen))
print(list(gen))

Answer: [0, 1, 2] and []

๐Ÿ’ก Explanation: Generators in Python are iterators that exhaust their values upon consumption. The first `list(gen)` call consumes all values (0, 1, 2). The second call finds the generator exhausted, returning an empty list [].

10What is the main limitation of the Global Interpreter Lock (GIL) in CPython?

Answer: It prevents multiple native threads from executing Python bytecodes at once (restricting CPU-bound multi-threading).

๐Ÿ’ก Explanation: The GIL is a mutex protecting access to Python objects to prevent race conditions. It restricts execution of Python bytecodes to one thread at a time, limiting multi-threaded performance on multi-core processors. CPU-bound performance is optimized using multiprocessing or native C extensions.

11What is the difference between a list and a tuple?

Answer: Lists are mutable (changeable); tuples are immutable (fixed).

๐Ÿ’ก Explanation: Lists use [] and can be modified after creation. Tuples use () and cannot be changed, which makes them hashable and usable as dictionary keys.

12What is the difference between "is" and "==" in Python?

Answer: "==" compares values; "is" compares identity (same object in memory).

๐Ÿ’ก Explanation: a == b checks whether the values are equal. a is b checks whether both names refer to the exact same object.

13Are Python strings mutable?

Answer: No, strings are immutable.

๐Ÿ’ก Explanation: Once created, a string cannot be changed in place. Methods like .upper() return a new string rather than modifying the original.

14What is the output of bool("")?

Answer: False

๐Ÿ’ก Explanation: An empty string is "falsy". Empty containers ('', [], {}, ()), 0, and None all evaluate to False in a boolean context.

15What is the difference between the "/" and "//" operators?

Answer: "/" is float division; "//" is floor (integer) division.

๐Ÿ’ก Explanation: 7 / 2 gives 3.5, while 7 // 2 gives 3, flooring the result to the nearest lower whole number.

16What is the output of "3" * 3?

Answer: '333'

๐Ÿ’ก Explanation: Multiplying a string by an integer repeats it, so "3" * 3 concatenates the string three times.

17What is the difference between a set and a list?

Answer: A set is unordered and stores only unique elements; a list is ordered and allows duplicates.

๐Ÿ’ก Explanation: Sets remove duplicates automatically and offer fast membership tests, but do not support indexing.

18What does the None keyword represent?

Answer: The absence of a value (a null object).

๐Ÿ’ก Explanation: None is a singleton representing "no value". It is the default return value of a function without a return statement.

19How do you check the type of a variable?

Answer: Using type() or isinstance().

๐Ÿ’ก Explanation: type(x) returns the object's class. isinstance(x, int) is preferred for checks because it respects inheritance.

20What is the output of 10 % 3?

Answer: 1

๐Ÿ’ก Explanation: The modulo operator % returns the remainder of a division. 10 divided by 3 is 3 with a remainder of 1.

21What is an f-string?

Answer: A formatted string literal, prefixed with f, that embeds expressions inside {}.

๐Ÿ’ก Explanation: Introduced in Python 3.6, f"{name}" inserts the value of name directly into the string, which is fast and readable.

22What is the difference between append() and extend() on a list?

Answer: append() adds a single element; extend() adds each element of an iterable.

๐Ÿ’ก Explanation: [1,2].append([3,4]) gives [1,2,[3,4]], while [1,2].extend([3,4]) gives [1,2,3,4].

23What does the "in" operator do?

Answer: Tests membership (whether a value exists in a sequence).

๐Ÿ’ก Explanation: "a" in "cat" returns True. It works with strings, lists, tuples, sets, and dictionary keys.

24How do you reverse a string in Python?

Answer: Using slicing: s[::-1].

๐Ÿ’ก Explanation: The slice [::-1] steps through the string backwards, producing a reversed copy.

25What does str.strip() do?

Answer: Removes leading and trailing whitespace (or specified characters).

๐Ÿ’ก Explanation: " hi ".strip() returns "hi". Use lstrip() or rstrip() to trim only one side.

26How do you split a string into a list of words?

Answer: Using str.split().

๐Ÿ’ก Explanation: "a b c".split() returns ["a", "b", "c"]. By default it splits on any run of whitespace.

27How do you join a list of strings into one string?

Answer: Using str.join(), e.g. ", ".join(list).

๐Ÿ’ก Explanation: The separator string calls join on the iterable: ", ".join(["a","b"]) returns "a, b".

28What is the difference between str.find() and str.index()?

Answer: find() returns -1 if not found; index() raises a ValueError.

๐Ÿ’ก Explanation: Both return the position of a substring, but they differ in how they handle a missing substring.

29What does the "r" prefix do in r"\n"?

Answer: Creates a raw string where backslashes are treated literally.

๐Ÿ’ก Explanation: r"\n" is a two-character string (backslash + n), not a newline. Raw strings are common in regular expressions.

30How do you remove duplicates from a list?

Answer: Convert to a set and back: list(set(my_list)).

๐Ÿ’ก Explanation: set() drops duplicates but loses order. Use dict.fromkeys() to remove duplicates while preserving order.

31What does list.pop() do without an argument?

Answer: Removes and returns the last element.

๐Ÿ’ก Explanation: pop(i) removes the element at index i; pop() with no argument defaults to the last element.

32What is a dictionary comprehension?

Answer: A concise way to build a dict, e.g. {k: v for k, v in items}.

๐Ÿ’ก Explanation: {x: x**2 for x in range(3)} produces {0: 0, 1: 1, 2: 4}.

33How do you safely get a dictionary value without risking a KeyError?

Answer: Use dict.get(key, default).

๐Ÿ’ก Explanation: d.get("x", 0) returns 0 if "x" is missing, instead of raising a KeyError like d["x"] would.

34What does sorted() return compared to list.sort()?

Answer: sorted() returns a new list; list.sort() sorts in place and returns None.

๐Ÿ’ก Explanation: Use sorted() when you must keep the original order intact, and .sort() when in-place reordering is fine.

35How do you merge two dictionaries in Python 3.9+?

Answer: Using the | operator: d1 | d2.

๐Ÿ’ก Explanation: Python 3.9 added dict merging with |. Before that, {**d1, **d2} or d1.update(d2) were common.

36What is the difference between set.remove() and set.discard()?

Answer: remove() raises KeyError if the item is missing; discard() does not.

๐Ÿ’ก Explanation: Both delete an element from a set, but discard() fails silently when the item is absent.

37What does enumerate() do?

Answer: Yields (index, value) pairs while iterating.

๐Ÿ’ก Explanation: for i, v in enumerate(seq) gives both the index and the value on each iteration, avoiding manual counters.

38What does zip() do?

Answer: Combines multiple iterables element-wise into tuples.

๐Ÿ’ก Explanation: zip([1,2], [3,4]) yields (1,3) and (2,4). It stops at the shortest iterable.

39How do you count occurrences of items in a list efficiently?

Answer: Using collections.Counter.

๐Ÿ’ก Explanation: Counter(my_list) returns a dict-like object mapping each element to how many times it appears.

40What does the slice list[1:4] return?

Answer: Elements at indices 1, 2, and 3 (stop is exclusive).

๐Ÿ’ก Explanation: Slicing is start-inclusive and stop-exclusive, so list[1:4] returns three elements.

41What is *args used for in a function definition?

Answer: To accept any number of positional arguments as a tuple.

๐Ÿ’ก Explanation: def f(*args) collects extra positional arguments into a tuple named args.

42What is **kwargs used for?

Answer: To accept any number of keyword arguments as a dictionary.

๐Ÿ’ก Explanation: def f(**kwargs) collects extra keyword arguments into a dict named kwargs.

43What is a lambda function?

Answer: A small anonymous function defined with the lambda keyword.

๐Ÿ’ก Explanation: lambda x: x + 1 is a one-line function, often passed to map(), filter(), or sorted().

44What does the "global" keyword do?

Answer: Lets a function modify a variable in the global scope.

๐Ÿ’ก Explanation: Without "global x", assigning to x inside a function creates a new local variable instead of changing the global one.

45Can a Python function return multiple values?

Answer: Yes, by returning a tuple.

๐Ÿ’ก Explanation: return a, b returns a tuple that the caller can unpack: x, y = func().

46What does the "nonlocal" keyword do?

Answer: Lets a nested function modify a variable in the enclosing (non-global) scope.

๐Ÿ’ก Explanation: nonlocal rebinds a variable from the outer function's scope rather than creating a new local one.

47What is the LEGB rule for name resolution?

Answer: Local, Enclosing, Global, Built-in.

๐Ÿ’ก Explanation: Python resolves names in that order: local scope first, then enclosing functions, then module-global, then built-ins.

48What is recursion?

Answer: A function calling itself to solve a problem.

๐Ÿ’ก Explanation: Recursion needs a base case to stop. Python's default recursion limit is around 1000 to avoid stack overflow.

49What does the "self" parameter refer to in a method?

Answer: The current instance of the class.

๐Ÿ’ก Explanation: self is the conventional name for the instance automatically passed as the first argument to instance methods.

50What is inheritance in OOP?

Answer: A class deriving attributes and methods from a parent class.

๐Ÿ’ก Explanation: class Dog(Animal) makes Dog inherit from Animal, reusing and extending its behaviour.

51What is method overriding?

Answer: Redefining a parent class method in a child class.

๐Ÿ’ก Explanation: The child's version replaces the parent's when called on a child instance, enabling polymorphism.

52What is the difference between a classmethod and a staticmethod?

Answer: A classmethod receives the class (cls); a staticmethod receives neither self nor cls.

๐Ÿ’ก Explanation: @classmethod suits factory methods; @staticmethod is a plain utility function grouped inside a class.

53What does the __str__ method do?

Answer: Defines the human-readable string representation of an object.

๐Ÿ’ก Explanation: It is used by str() and print(). __repr__ instead provides an unambiguous, developer-facing representation.

54What does super() do?

Answer: Calls a method from the parent class.

๐Ÿ’ก Explanation: super().__init__() invokes the parent's constructor, commonly used to initialise inherited attributes.

55What is the difference between a class variable and an instance variable?

Answer: A class variable is shared by all instances; an instance variable is unique to each object.

๐Ÿ’ก Explanation: Class variables are defined at class level; instance variables are usually set on self inside __init__.

56What is polymorphism?

Answer: Different objects responding to the same method call in their own way.

๐Ÿ’ก Explanation: Calling .area() on Circle and Square objects runs each class's own implementation of the method.

57What does a leading double underscore (__x) do to an attribute?

Answer: Triggers name mangling to make it harder to access from outside.

๐Ÿ’ก Explanation: Python renames __x to _ClassName__x, providing a weak form of "private" attribute by convention.

58What is the main advantage of a generator over a list?

Answer: It produces items lazily, using far less memory.

๐Ÿ’ก Explanation: Generators yield one item at a time instead of building the entire sequence in memory at once.

59What keyword turns a function into a generator?

Answer: yield

๐Ÿ’ก Explanation: A function containing yield returns a generator object; execution pauses and resumes at each yield.

60How do you create a generator expression?

Answer: Use parentheses: (x for x in iterable).

๐Ÿ’ก Explanation: Generator expressions look like comprehensions but use () and evaluate lazily instead of building a list.

61What does next() do with a generator?

Answer: Retrieves the next value, advancing the generator.

๐Ÿ’ก Explanation: next(gen) resumes execution until the next yield, and raises StopIteration when the generator is exhausted.

62What is a decorator?

Answer: A function that wraps another function to extend its behaviour.

๐Ÿ’ก Explanation: Decorators use the @ syntax: they take a function, add functionality, and return a new function.

63What is a closure?

Answer: A nested function that remembers variables from its enclosing scope.

๐Ÿ’ก Explanation: The inner function retains access to the outer function's variables even after the outer function has returned.

64What does the @property decorator do?

Answer: Lets a method be accessed like an attribute.

๐Ÿ’ก Explanation: @property turns a getter method into a read-only computed attribute accessed without parentheses.

65What does functools.wraps do inside a decorator?

Answer: Preserves the wrapped function's name and docstring.

๐Ÿ’ก Explanation: Without @wraps, the decorated function loses its original __name__ and __doc__ metadata.

66Are functions first-class objects in Python?

Answer: Yes.

๐Ÿ’ก Explanation: Functions can be assigned to variables, passed as arguments, and returned from other functions.

67Which block always runs whether or not an exception occurs?

Answer: The finally block.

๐Ÿ’ก Explanation: finally is used for cleanup such as closing files or releasing locks, and runs regardless of exceptions.

68How do you handle a specific exception type?

Answer: Use try/except with that exception, e.g. except ValueError.

๐Ÿ’ก Explanation: A bare except: catches everything and is discouraged because it can hide bugs.

69What does the "raise" keyword do?

Answer: Manually triggers (raises) an exception.

๐Ÿ’ก Explanation: raise ValueError("bad input") stops normal flow and signals an error to be handled by a try/except.

70What does the "else" clause of a try statement do?

Answer: Runs only if no exception was raised in the try block.

๐Ÿ’ก Explanation: It keeps success-only code separate from the error-handling code in except.

71What is the base class of most built-in exceptions?

Answer: Exception (which inherits from BaseException).

๐Ÿ’ก Explanation: Custom exceptions should subclass Exception, not BaseException, to behave like standard errors.

72How do you import a specific function from a module?

Answer: Using "from module import function".

๐Ÿ’ก Explanation: from math import sqrt lets you call sqrt() directly without the math. prefix.

73What does "if __name__ == '__main__':" do?

Answer: Runs code only when the file is executed directly, not when imported.

๐Ÿ’ก Explanation: This guard prevents a module's script code from running when the module is imported elsewhere.

74Which module provides random number functions?

Answer: The random module.

๐Ÿ’ก Explanation: random.randint(), random.choice(), and random.shuffle() are commonly used functions from it.

75Which module is used for regular expressions?

Answer: The re module.

๐Ÿ’ก Explanation: re.match(), re.search(), and re.findall() provide pattern-matching functionality.

76What does pip do?

Answer: Installs and manages third-party Python packages.

๐Ÿ’ก Explanation: pip install <package> downloads packages from PyPI, the Python Package Index.

77What is a virtual environment used for?

Answer: To isolate a project's dependencies from other projects.

๐Ÿ’ก Explanation: Tools like venv create isolated environments so package versions do not conflict across projects.

78What is the output of: print(2 ** 3 ** 2)?

Answer: 512

๐Ÿ’ก Explanation: The ** operator is right-associative, so it evaluates as 2 ** (3 ** 2) = 2 ** 9 = 512.

79What is the output of: print(bool(0), bool([]), bool("0"))?

Answer: False False True

๐Ÿ’ก Explanation: 0 and [] are falsy, but the non-empty string "0" is truthy โ€” any non-empty string evaluates to True.

80What is the output of: print([1, 2, 3][-1])?

Answer: 3

๐Ÿ’ก Explanation: Negative indexing counts from the end, so index -1 is the last element.

81What is the output of: print("5" + "5")?

Answer: '55'

๐Ÿ’ก Explanation: The + operator concatenates strings. Numeric addition would need int("5") + int("5") = 10.

82What is the output of: print(list(range(1, 10, 2)))?

Answer: [1, 3, 5, 7, 9]

๐Ÿ’ก Explanation: range(start, stop, step) with step 2 yields every second number from 1 up to (not including) 10.

83What is the output of: print(3 == 3.0)?

Answer: True

๐Ÿ’ก Explanation: Python compares numeric values across types, so the integer 3 equals the float 3.0.

84What is the output of: print("abc"[::2])?

Answer: 'ac'

๐Ÿ’ก Explanation: The slice [::2] takes every second character starting at index 0.

85What is the output of: x = [1,2,3]; y = x; y.append(4); print(x)?

Answer: [1, 2, 3, 4]

๐Ÿ’ก Explanation: y = x makes both names reference the same list object, so appending through y also changes x.

86What is the output of: print(type(5 / 2))?

Answer: <class 'float'>

๐Ÿ’ก Explanation: The / operator always returns a float in Python 3, even when the operands divide evenly.

87What is the output of: print("Python".lower().upper())?

Answer: 'PYTHON'

๐Ÿ’ก Explanation: Method chaining: .lower() returns "python", then .upper() returns "PYTHON".

88What is the output of: print(len({1, 1, 2, 3, 3}))?

Answer: 3

๐Ÿ’ก Explanation: A set literal removes duplicates, leaving {1, 2, 3}, which has length 3.

89What is the output of: print(1 == True)?

Answer: True

๐Ÿ’ก Explanation: bool is a subclass of int in Python, where True equals 1 and False equals 0.

90What is the difference between "==" for lists and "is" for lists?

Answer: "==" checks equal contents; "is" checks they are the same object.

๐Ÿ’ก Explanation: [1,2] == [1,2] is True, but [1,2] is [1,2] is False because they are two distinct list objects.

91What does the * operator do in a call like func(*my_list)?

Answer: Unpacks the iterable into separate positional arguments.

๐Ÿ’ก Explanation: func(*[1,2,3]) is equivalent to func(1, 2, 3). Similarly ** unpacks a dict into keyword arguments.

92What does a slice assignment like list[:] = [] do?

Answer: Clears the list in place while keeping the same object.

๐Ÿ’ก Explanation: It empties the existing list object, so other references to that list also see it become empty.

93What is the difference between deepcopy and assignment for nested lists?

Answer: Assignment shares the same object; deepcopy creates fully independent nested copies.

๐Ÿ’ก Explanation: copy.deepcopy() recursively copies nested objects so changes to the copy do not affect the original.

94What does the walrus operator := do?

Answer: Assigns a value as part of an expression.

๐Ÿ’ก Explanation: Added in Python 3.8, it lets you assign and use a value at once, e.g. if (n := len(data)) > 10:.

95What is the output of: print("hello".replace("l", "L"))?

Answer: 'heLLo'

๐Ÿ’ก Explanation: replace() returns a new string with all occurrences of the substring replaced (both l characters here).

96What does the map() function do?

Answer: Applies a function to every item of an iterable, returning a map object.

๐Ÿ’ก Explanation: list(map(str, [1,2,3])) returns ["1","2","3"]. Wrap it in list() to see the results.

97What does the filter() function do?

Answer: Keeps only items for which a function returns True.

๐Ÿ’ก Explanation: list(filter(lambda x: x > 0, [-1, 2, -3, 4])) returns [2, 4].

98What does the "pass" statement do?

Answer: Nothing โ€” it is a placeholder where a statement is syntactically required.

๐Ÿ’ก Explanation: pass is used in empty function bodies, loops, or class definitions you intend to fill in later.

99What is the output of: print(bool(None))?

Answer: False

๐Ÿ’ก Explanation: None is falsy, so bool(None) evaluates to False.

100What does dict.items() return?

Answer: A view of (key, value) pairs.

๐Ÿ’ก Explanation: for k, v in d.items() iterates over both keys and values together. keys() and values() return the parts separately.

Best Practices for Python Interviews

  • Write readable PEP 8 compliant code - Name variables clearly and use space formatting.
  • Understand complexity overheads - Know time complexities (O-notation) for dictionary lookups, list inserts, and sorting.
  • Master built-in libraries - Be proficient with itertools, collections, and copy modules.
  • Focus on error exceptions - Handle errors gracefully with try-except-finally context guards.

Practice Live Code Quizzes

Ready to validate your technical knowledge? Take our live Computer Science Quiz to test your concepts in programming, database design, and systems engineering!

Train Your Programming Skills

Play our interactive Computer Science and programming assessment online!

โšก Play Computer Science Quiz
โœ๏ธ
QuizOxa Editorial Team

Our programming and technical interview guides are curated by senior software engineering leads to ensure accurate code compilation and logic explanations.

๐Ÿ“šRelated Articles

1
๐Ÿ“„
Free IQ Test: How Smart Are You? Ultimate Cognitive Guide
Test your logic quotient with standard pattern, puzzle, and analogy questions.
2
๐Ÿ“„
Which Anime Character Are You? Ultimate Personality Quiz
Find your anime twin based on personality traits, strengths, and weaknesses.
3
๐Ÿ“„
Which Marvel Character Are You? Take the Ultimate Quiz
Are you brave like Captain America or smart like Tony Stark?

๐ŸŽฏTry These Quizzes

๐Ÿ’ป
Computer Science Quiz
๐Ÿ“30 questions
๐Ÿ”Œ
Technology Quiz
๐Ÿ“50 questions
๐Ÿง 
General Knowledge Quiz
๐Ÿ“100 questions