AbairTechSolutionDIGITAL SOLUTIONS FOR A SMARTER TOMORROW

Menu

Home › Programming MCQs › Python

Python 3 · 40 MCQs with explanations

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.

Type Example Mutable? Ordered?
list [1, 2, 3] Yes Yes
tuple (1, 2, 3) No Yes
dict {"a": 1} Yes Yes (insertion order, Python 3.7+)
set {1, 2, 3} Yes No
str "abc" No Yes
1–10 Basics & operators11–20 Strings & collections21–30 Functions & OOP31–40 Built-ins & tooling

Questions 1–10: basics, operators and control flow

1. What does print(type([])) output?

  1. <class ‘tuple’>
  2. <class ‘list’>
  3. <class ‘array’>
  4. <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?

  1. tuple
  2. list
  3. dict
  4. 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?

  1. 3.5
  2. 4
  3. 1
  4. 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?

  1. 6
  2. 8
  3. 9
  4. 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 ==?

  1. is checks identity (same object); == checks equal values
  2. They are identical
  3. == checks identity; is checks values
  4. 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. 1, 3, 6, 9
  2. 1, 4, 7, 10
  3. 1, 4, 7
  4. 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?

  1. It returns 8
  2. It returns “53”
  3. It returns “8”
  4. 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([])?

  1. True
  2. False
  3. None
  4. 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?

  1. if x == None:
  2. if x = None:
  3. if x is None:
  4. 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?

  1. Curly braces
  2. BEGIN and END keywords
  3. Semicolons
  4. 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]?

  1. “pyt”
  2. “ytho”
  3. “yth”
  4. “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]?

  1. “n”
  2. “p”
  3. “o”
  4. 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. [1, 4, 9, 16]
  2. [0, 1, 2, 3]
  3. [0, 2, 4, 6]
  4. [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})?

  1. 5
  2. 3
  3. 2
  4. 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?

  1. A string
  2. An integer
  3. A tuple of numbers
  4. 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?

  1. A KeyError
  2. None
  3. 0
  4. “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()?

  1. sorted() returns a new list; sort() changes the list in place and returns None
  2. They are identical
  3. sort() returns a new list
  4. 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. [1, 2]
  2. [1, 2, 3]
  3. [3]
  4. 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?

  1. When copying a string
  2. When copying an integer
  3. When the object contains nested mutable objects, such as a list of lists
  4. 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?

  1. “Total: {2 + 3}”
  2. “Total: 2 + 3”
  3. An error
  4. “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)?

  1. [2]
  2. [1, 2]
  3. []
  4. 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?

  1. A dictionary of keyword arguments
  2. A list of required arguments
  3. A tuple of extra positional arguments
  4. A pointer
Show answer

Answer: C. def total(*args): return sum(args) accepts any number of values.

23. Inside a function, what is **kwargs?

  1. A dictionary of extra keyword arguments
  2. A tuple of positional arguments
  3. The function’s return value
  4. An exponent operator
Show answer

Answer: A. Calling f(city="Lahore", age=30) gives kwargs == {"city": "Lahore", "age": 30}.

24. When does a finally block run?

  1. Only when an exception occurs
  2. Only when no exception occurs
  3. Only if there is an else block
  4. Always, whether or not an exception occurred
Show answer

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?

  1. Python requires alphabetical order
  2. Handlers are checked in order, and the general one would catch everything first
  3. ValueError is not a subclass of Exception
  4. 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:?

  1. The file opens faster
  2. The file is read into memory at once
  3. The file is closed automatically, even if an error occurs
  4. 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?

  1. It uses yield
  2. It returns a list
  3. It has no parameters
  4. 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?

  1. A function that deletes the object
  2. A private variable
  3. The method that prints the object
  4. 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?

  1. The class itself
  2. The current instance (object)
  3. The parent class
  4. 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?

  1. Creates a new parent object
  2. Deletes the parent’s attributes
  3. Calls the parent class’s __init__ method
  4. 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?

  1. A function that takes another function and returns a modified version, applied with @
  2. A comment style
  3. A way to format strings
  4. 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?

  1. A module for maths
  2. A loop keyword
  3. A type of list
  4. 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. [1, 2, 3]
  2. [‘1’, ‘2’, ‘3’]
  3. ‘123’
  4. 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?

  1. Only the values
  2. Only the indexes
  3. Pairs of (index, value): (0, “a”), (1, “b”)
  4. 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. [(1, ‘a’), (2, ‘b’), (3, None)]
  2. An error, because the lengths differ
  3. [1, 2, 3, ‘a’, ‘b’]
  4. [(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?

  1. 10
  2. “73”
  3. “10”
  4. 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?

  1. Defines the main class
  2. Runs the code below it only when the file is executed directly, not when it is imported
  3. Makes the script run faster
  4. 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?

  1. Threads cannot be created
  2. Each thread runs in its own process
  3. Only one thread executes Python bytecode at a time, so CPU-heavy work does not speed up with threads
  4. 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?

  1. python -m venv .venv
  2. pip create env
  3. python --env new
  4. 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?

  1. Creates a new Python file called requests
  2. Upgrades Python
  3. Imports requests into the current script
  4. 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.

Our ServicesMore MCQs