Python MCQ Questions and Answers: 40 Practice Questions with Explanations
By AbairTech Solution · For students, job seekers and working developers
Published by AbairTech Solution · Reviewed November 2026 · Editorial policy
How to use this page. All questions use Python 3. For questions that show code, work out the output yourself before opening the answer – or paste the code into a Python shell and check. Running small snippets is the fastest way to learn Python.
Python study notes
Python is popular for automation, data analysis, web back ends and AI because its syntax is short and readable. Most beginner and interview mistakes come from a few core ideas, so it is worth reviewing them first.
Indentation is syntax. Python uses indentation, not braces, to mark blocks. Mixing tabs and spaces or misaligning lines raises an IndentationError.
Everything is an object. Variables are names that point to objects. == compares values; is checks whether two names point to the same object.
Mutable vs immutable. Lists, dictionaries and sets can change in place; integers, strings and tuples cannot. This explains many “why did my list change?” bugs.
Truthiness. Empty containers ([], {}, ""), 0 and None are false in an if test; almost everything else is true.
Questions 1–10: basics, operators and control flow
1. What does print(type([])) output?
<class ‘tuple’>
<class ‘list’>
<class ‘array’>
<class ‘dict’>
Show answer
Answer: B. Square brackets create a list. () creates an empty tuple and {} an empty dictionary (not a set).
2. Which of these types is immutable?
tuple
list
dict
set
Show answer
Answer: A – tuple. Once created, a tuple’s items cannot be reassigned. That is why tuples can be dictionary keys and lists cannot.
3. What is the value of 7 // 2?
3.5
4
1
3
Show answer
Answer: D – 3.// is floor division. 7 / 2 gives 3.5 and 7 % 2 gives the remainder, 1.
4. What is 2 ** 3?
6
8
9
5
Show answer
Answer: B – 8.** is the power operator. ^ is bitwise XOR, not power, a common mistake.
5. What is the difference between is and ==?
is checks identity (same object); == checks equal values
They are identical
== checks identity; is checks values
is only works with strings
Show answer
Answer: A. Two separate lists [1] and [1] are equal (== is True) but not the same object (is is False). Use is mainly for None.
6. Which numbers does range(1, 10, 3) produce?
1, 3, 6, 9
1, 4, 7, 10
1, 4, 7
3, 6, 9
Show answer
Answer: C – 1, 4, 7. range starts at 1, steps by 3 and stops before 10 – the end value is never included.
7. What happens when you run "5" + 3?
It returns 8
It returns “53”
It returns “8”
It raises a TypeError
Show answer
Answer: D. Python does not silently convert between strings and numbers. Use int("5") + 3 or "5" + str(3).
8. What is bool([])?
True
False
None
An error
Show answer
Answer: B – False. Empty containers are falsy, so if my_list: is the Pythonic way to check that a list is not empty.
9. How should you check whether a variable x is None?
if x == None:
if x = None:
if x is None:
if None(x):
Show answer
Answer: C. None is a single object, so an identity check is correct and recommended by PEP 8. == usually works but can be overridden by a class.
10. What does Python use to define a code block, such as the body of an if?
Curly braces
BEGIN and END keywords
Semicolons
Indentation
Show answer
Answer: D. Lines with the same indentation (PEP 8 recommends 4 spaces) form a block, after a line ending with a colon.
Questions 11–20: strings, lists, dictionaries and sets
11. What is "python"[1:4]?
“pyt”
“ytho”
“yth”
“pyth”
Show answer
Answer: C – “yth”. Slicing starts at index 1 (“y”) and stops before index 4, so it takes indexes 1, 2 and 3.
12. What is "python"[-1]?
“n”
“p”
“o”
An IndexError
Show answer
Answer: A – “n”. Negative indexes count from the end; -1 is the last character.
13. What does [x * x for x in range(4)] produce?
[1, 4, 9, 16]
[0, 1, 2, 3]
[0, 2, 4, 6]
[0, 1, 4, 9]
Show answer
Answer: D. range(4) gives 0, 1, 2, 3, and each value is squared. List comprehensions are a short, fast way to build lists.
14. What is len({1, 2, 2, 3, 3})?
5
3
2
An error
Show answer
Answer: B – 3. Sets keep only unique values, so the duplicates disappear. list(set(items)) is a quick way to remove duplicates (but loses order).
15. Which of these cannot be used as a dictionary key?
A string
An integer
A tuple of numbers
A list
Show answer
Answer: D – a list. Keys must be hashable, which requires immutability. A list can change, so its hash could change; Python raises TypeError: unhashable type.
16. What does prices.get("tea", 0) return if “tea” is not a key?
A KeyError
None
0
“tea”
Show answer
Answer: C – 0. get() returns the default instead of raising an error. prices["tea"] would raise a KeyError.
17. What is the difference between sorted(nums) and nums.sort()?
sorted() returns a new list; sort() changes the list in place and returns None
They are identical
sort() returns a new list
sorted() only works on strings
Show answer
Answer: A. A classic bug is nums = nums.sort(), which sets nums to None.
18.b = a where a = [1, 2]. Then b.append(3). What is a?
[1, 2]
[1, 2, 3]
[3]
An error
Show answer
Answer: B – [1, 2, 3]. Assignment does not copy; both names point to the same list. Use a.copy() or list(a) for a separate list.
19. When do you need copy.deepcopy() rather than a normal copy?
When copying a string
When copying an integer
When the object contains nested mutable objects, such as a list of lists
Never; they behave the same
Show answer
Answer: C. A shallow copy creates a new outer list but shares the inner lists. deepcopy copies every level.
20. What does f"Total: {2 + 3}" evaluate to?
“Total: {2 + 3}”
“Total: 2 + 3”
An error
“Total: 5”
Show answer
Answer: D. f-strings evaluate expressions inside braces. They are the preferred way to format strings in modern Python.
Questions 21–30: functions, exceptions and classes
21. Given def add(item, bag=[]): bag.append(item); return bag, what does the second call add(2) return after add(1)?
[2]
[1, 2]
[]
An error
Show answer
Answer: B – [1, 2]. Default values are created once, when the function is defined, so the same list is reused. Use bag=None and create a new list inside the function.
22. Inside a function, what is *args?
A dictionary of keyword arguments
A list of required arguments
A tuple of extra positional arguments
A pointer
Show answer
Answer: C.def total(*args): return sum(args) accepts any number of values.
Answer: D. finally is for clean-up such as closing connections. The else block runs only when no exception was raised.
25. Why should except ValueError come before except Exception?
Python requires alphabetical order
Handlers are checked in order, and the general one would catch everything first
ValueError is not a subclass of Exception
The order does not matter
Show answer
Answer: B. Put specific exceptions first. Avoid a bare except:, which also catches KeyboardInterrupt and hides bugs.
26. What is the main benefit of with open("data.txt") as f:?
The file opens faster
The file is read into memory at once
The file is closed automatically, even if an error occurs
The file is locked for other programs
Show answer
Answer: C. The with statement uses a context manager, which also works for database connections and locks.
27. What makes a function a generator?
It uses yield
It returns a list
It has no parameters
It is decorated with @generator
Show answer
Answer: A. Generators produce values one at a time, so they can process huge files or endless streams without loading everything into memory.
28. What is __init__ in a class?
A function that deletes the object
A private variable
The method that prints the object
The method that initialises a new object’s attributes
Show answer
Answer: D. It runs automatically when you create an instance, for example Invoice(1001, 2500).
29. In a method, what does self refer to?
The class itself
The current instance (object)
The parent class
The module
Show answer
Answer: B. Python passes the instance automatically as the first argument. The name self is a convention, not a keyword.
30. What does super().__init__(name) do in a child class?
Creates a new parent object
Deletes the parent’s attributes
Calls the parent class’s __init__ method
Makes the class abstract
Show answer
Answer: C. It lets the parent set up its attributes before the child adds its own, without repeating code.
Questions 31–40: built-ins, decorators and tooling
31. What is a decorator?
A function that takes another function and returns a modified version, applied with @
A comment style
A way to format strings
A class attribute
Show answer
Answer: A. Decorators add behaviour such as logging, timing, caching (@functools.cache) or login checks in web frameworks.
32. What is a lambda?
A module for maths
A loop keyword
A type of list
A small anonymous function limited to one expression
Show answer
Answer: D. Commonly used as a sort key: sorted(staff, key=lambda s: s["salary"]).
33. What is list(map(str, [1, 2, 3]))?
[1, 2, 3]
[‘1’, ‘2’, ‘3’]
‘123’
An error
Show answer
Answer: B. map applies str to each item. In Python 3 map returns a lazy iterator, so list() is needed to see the values.
34. What does enumerate(["a", "b"]) give you in a for loop?
Only the values
Only the indexes
Pairs of (index, value): (0, “a”), (1, “b”)
The length
Show answer
Answer: C.for i, item in enumerate(items, start=1): is cleaner than managing a counter yourself.
35. What is list(zip([1, 2, 3], ["a", "b"]))?
[(1, ‘a’), (2, ‘b’), (3, None)]
An error, because the lengths differ
[1, 2, 3, ‘a’, ‘b’]
[(1, ‘a’), (2, ‘b’)]
Show answer
Answer: D. zip stops at the shortest input. Use itertools.zip_longest to fill gaps, or zip(..., strict=True) (Python 3.10+) to raise an error.
36. What is int("7") + 3?
10
“73”
“10”
A TypeError
Show answer
Answer: A – 10. int() converts the string to a number first. int("7.5") would raise a ValueError; use float() for decimals.
37. What does if __name__ == "__main__": do?
Defines the main class
Runs the code below it only when the file is executed directly, not when it is imported
Makes the script run faster
Is required in every Python file
Show answer
Answer: B. It lets a file work both as a reusable module and as a runnable script.
38. In CPython, what does the Global Interpreter Lock (GIL) mean for threads?
Threads cannot be created
Each thread runs in its own process
Only one thread executes Python bytecode at a time, so CPU-heavy work does not speed up with threads
Threads always run in parallel on all cores
Show answer
Answer: C. Threads still help for I/O-bound work such as network calls. For CPU-bound work, use multiprocessing. Newer CPython releases also offer an optional free-threaded build.
39. Which command creates a virtual environment?
python -m venv .venv
pip create env
python --env new
venv install
Show answer
Answer: A. A virtual environment keeps each project’s packages separate, so upgrading a library for one project does not break another.
40. What does pip install requests do?
Creates a new Python file called requests
Upgrades Python
Imports requests into the current script
Downloads and installs the requests package from the Python Package Index (PyPI)
Show answer
Answer: D. After installing, you still need import requests in your code. Record dependencies in requirements.txt or pyproject.toml.
What to practise next
If you missed questions on mutability (18, 19, 21), spend time there – those ideas cause the most real-world Python bugs. Then try the JavaScript MCQs or the SQL MCQs, since most Python jobs also need SQL. All topics are on the Programming MCQs hub.
Need custom software or automation?
AbairTech builds business software, APIs, integrations and automation for companies in Pakistan and abroad.
This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.
Strictly Necessary Cookies
Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.
If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.