Quiz#

This quiz covers the key concepts from Lecture 3: Python Fundamentals – Part II, including loops, the range() function, iterables, lists, tuples, dictionaries, sets, and comprehensions.

Note

Instructions:

  • Answer all questions to the best of your ability.

  • Multiple choice questions have exactly one correct answer.

  • True/False questions require you to determine if the statement is correct.

  • Essay questions require short written responses (2-4 sentences).

  • Click the dropdown after each question to reveal the answer.


Multiple Choice#

Question 1

What is the output of list(range(2, 10, 3))?

  1. [2, 5, 8, 11]

  2. [2, 5, 8]

  3. [2, 4, 6, 8]

  4. [3, 6, 9]

Answer

B[2, 5, 8]

range(2, 10, 3) starts at 2, increments by 3, and stops before 10. Values: 2, 5, 8 (11 would exceed 10).

Question 2

Which of the following correctly creates an empty set?

  1. empty = {}

  2. empty = set()

  3. empty = []

  4. empty = set{}

Answer

Bempty = set()

{} creates an empty dictionary, not a set. Use set() for an empty set.

Question 3

What is the output of the following code?

nums = [1, 2, 3]
result = nums.append(4)
print(result)
  1. [1, 2, 3, 4]

  2. 4

  3. None

  4. [4]

Answer

CNone

append() modifies the list in-place and returns None. The list is changed, but the return value is None.

Question 4

Which method would you use to safely access a dictionary key that might not exist?

  1. dict[key]

  2. dict.get(key)

  3. dict.find(key)

  4. dict.access(key)

Answer

Bdict.get(key)

.get() returns None (or a default value) if the key doesn’t exist, while dict[key] raises KeyError.

Question 5

What is the output of (1, 2, 3) + (4, 5)?

  1. [1, 2, 3, 4, 5]

  2. (1, 2, 3, 4, 5)

  3. TypeError

  4. ((1, 2, 3), (4, 5))

Answer

B(1, 2, 3, 4, 5)

The + operator concatenates tuples, creating a new tuple with all elements.

Question 6

What does the else clause do when attached to a for loop?

  1. Executes if the loop encounters an error.

  2. Executes if the loop completes without hitting break.

  3. Executes on every iteration after the main body.

  4. Executes if the loop body is empty.

Answer

B – Executes if the loop completes without hitting break.

The else clause runs only if the loop exits normally (not via break). Useful for search patterns.

Question 7

What is the output of the following list comprehension?

result = [x * 2 for x in range(5) if x % 2 == 0]
print(result)
  1. [0, 2, 4, 6, 8]

  2. [0, 4, 8]

  3. [2, 4, 6, 8, 10]

  4. [0, 2, 4]

Answer

B[0, 4, 8]

The comprehension filters for even numbers (0, 2, 4) and doubles them (0, 4, 8).

Question 8

Given a = {1, 2, 3} and b = {2, 3, 4}, what is a & b?

  1. {1, 2, 3, 4}

  2. {2, 3}

  3. {1, 4}

  4. {1}

Answer

B{2, 3}

& is the intersection operator, returning elements present in both sets.

Question 9

What is the correct way to create a single-element tuple?

  1. t = (42)

  2. t = (42,)

  3. t = tuple(42)

  4. t = [42]

Answer

Bt = (42,)

The trailing comma is required for single-element tuples. (42) is just the integer 42 in parentheses.

Question 10

What does the continue statement do inside a loop?

  1. Exits the loop entirely.

  2. Skips to the next iteration of the loop.

  3. Restarts the loop from the beginning.

  4. Pauses the loop until a condition is met.

Answer

B – Skips to the next iteration of the loop.

continue immediately starts the next iteration, skipping any remaining code in the current iteration.

Question 11

What is the output of the following code?

d = {"a": 1, "b": 2}
print(list(d.keys()))
  1. ["a", "b"]

  2. [1, 2]

  3. [("a", 1), ("b", 2)]

  4. {"a", "b"}

Answer

A["a", "b"]

.keys() returns a view of dictionary keys, which list() converts to a list.

Question 12

Why is range() considered memory efficient?

  1. It stores all values in compressed format.

  2. It generates values on demand (lazy evaluation).

  3. It uses special integer optimization.

  4. It automatically garbage collects unused values.

Answer

B – It generates values on demand (lazy evaluation).

range() only stores start, stop, and step (48 bytes total). Values are computed when needed.

Question 13

What is the output of the following code?

from copy import copy
a = [1, [2, 3]]
b = copy(a)
b[1].append(4)
print(a)
  1. [1, [2, 3]]

  2. [1, [2, 3, 4]]

  3. [1, [4]]

  4. TypeError

Answer

B[1, [2, 3, 4]]

Shallow copy copies references to nested objects. b[1] and a[1] point to the same inner list.

Question 14

Which of the following is NOT a valid way to iterate over a dictionary’s key-value pairs?

  1. for k, v in d.items():

  2. for k in d: v = d[k]

  3. for k, v in d:

  4. for (k, v) in d.items():

Answer

Cfor k, v in d:

Iterating directly over a dictionary yields only keys, not key-value pairs. Use .items() for pairs.

Question 15

What is the output of [1, 2, 3][1:1]?

  1. [1]

  2. [2]

  3. []

  4. [1, 2]

Answer

C[]

Slice [1:1] has start equal to stop, resulting in an empty list.


True or False#

Question 16

True or False: Lists in Python are mutable, meaning you can change their elements after creation.

Answer

True

Lists are mutable. You can modify, add, or remove elements using methods like append(), pop(), or direct index assignment.

Question 17

True or False: Dictionaries in Python 3.7+ maintain insertion order.

Answer

True

Since Python 3.7, dictionaries maintain insertion order as part of the language specification.

Question 18

True or False: The expression 5 in range(1, 10, 2) evaluates to True.

Answer

True

range(1, 10, 2) produces the sequence 1, 3, 5, 7, 9. The value 5 is in this range, so the expression evaluates to True. The in operator on range objects runs in O(1) constant time.

Question 19

True or False: Tuples can be used as dictionary keys because they are immutable and hashable.

Answer

True

Tuples are immutable and hashable (if all their elements are hashable), making them valid dictionary keys.

Question 20

True or False: enumerate() returns a list of tuples containing index-value pairs.

Answer

False

enumerate() returns an enumerate object (an iterator), not a list. Convert with list() to get a list of tuples.

Question 21

True or False: The pop() method on a list modifies the list in-place and returns the removed element.

Answer

True

pop() removes an element at a given index (default: last), modifies the list in-place, and returns the removed value.

Question 22

True or False: Set elements must be unique, but they can be of any type including lists.

Answer

False

Set elements must be hashable. Lists are mutable and unhashable, so they cannot be set elements.

Question 23

True or False: The expression range(5) == range(0, 5, 1) evaluates to True.

Answer

True

Two ranges are equal if they produce the same sequence. range(5) and range(0, 5, 1) both produce [0, 1, 2, 3, 4].

Question 24

True or False: Using a = b where b is a list creates an independent copy of the list.

Answer

False

a = b creates an alias – both names reference the same object. Use copy() or slicing for an independent copy.

Question 25

True or False: Dictionary comprehensions can include conditional filtering similar to list comprehensions.

Answer

True

Dictionary comprehensions support if conditions: {k: v for k, v in items if condition}.


Essay Questions#

Question 26

Explain the difference between shallow copy and deep copy for nested lists. Provide an example showing when shallow copy might cause unexpected behavior.

(2-4 sentences)

Answer Guidelines

Key points to include:

  • Shallow copy creates a new object but copies references to nested objects, not the objects themselves.

  • Deep copy recursively copies all nested objects, creating completely independent copies.

  • Example: a = [1, [2, 3]]; b = copy(a); b[1].append(4) modifies both a and b’s inner list.

  • Use deepcopy() when you need truly independent copies of nested structures.

Question 27

Describe when you would choose a tuple over a list. Give at least two practical scenarios where tuples are the better choice.

(2-4 sentences)

Answer Guidelines

Key points to include:

  • Tuples are immutable, making them hashable and usable as dictionary keys.

  • Use tuples for fixed collections where the data shouldn’t change (coordinates, RGB values, database records).

  • Tuples signal intent – readers know the data is meant to be constant.

  • Tuples are slightly faster than lists and use less memory.

  • Example scenarios: function returning multiple values, dictionary keys, data that represents a fixed record.

Question 28

Explain why range() is memory efficient compared to creating a list of the same values. How does this affect performance when iterating over large sequences?

(2-4 sentences)

Answer Guidelines

Key points to include:

  • range() is a lazy iterator that only stores start, stop, and step (48 bytes regardless of size).

  • A list stores every value in memory (8+ bytes per integer).

  • For range(1000000): range uses 48 bytes; equivalent list uses ~8 MB.

  • This matters when iterating over large sequences – range() has constant memory usage.

Question 29

Compare and contrast for loops and while loops. When would you prefer one over the other? Provide an example use case for each.

(3-5 sentences)

Answer Guidelines

Key points to include:

  • for loops iterate over known sequences or ranges – best when you know how many iterations.

  • while loops continue until a condition is false – best when iteration count is unknown.

  • for is preferred for iterating over collections (lists, strings, dicts).

  • while is preferred for user input validation, reading until EOF, or state-based loops.

  • Example for: processing each item in a list. Example while: prompting until valid input.

Question 30

Explain the difference between in-place and out-of-place operations using list methods as examples. Why is it important to know which type a method uses?

(2-4 sentences)

Answer Guidelines

Key points to include:

  • In-place methods modify the original object and return None (e.g., list.sort(), list.append()).

  • Out-of-place methods return a new object, leaving the original unchanged (e.g., sorted(), str.upper()).

  • Important because assigning an in-place result often leads to bugs: x = x.sort() sets x to None.

  • Check documentation or test return values to know which type a method uses.