After q.popleft(), q becomes [20, 30], so q[0] is now 20.
Final Answer:
10\n20 -> Option D
Quick Check:
First peek 10, after removal peek 20 [OK]
Hint: Peek before and after popleft to see front change [OK]
Common Mistakes:
Assuming front stays same after popleft
Confusing popleft with pop
Printing wrong elements
4. Identify the error in the following code that tries to peek the front element of a queue:
from queue import Queue
q = Queue()
q.put(5)
q.put(10)
print(q[0])
medium
A. print statement syntax error
B. Queue is empty, cannot peek
C. Queue object does not support indexing
D. put() method is incorrect
Solution
Step 1: Understand Queue class behavior
Python's queue.Queue does not support direct indexing like q[0].
Step 2: Identify correct peek method
To peek, one must use q.queue[0] or other methods, but direct q[0] causes error.
Final Answer:
Queue object does not support indexing -> Option C
Quick Check:
queue.Queue no indexing [OK]
Hint: queue.Queue objects can't use q[0] indexing [OK]
Common Mistakes:
Trying to index queue.Queue directly
Assuming put() is wrong
Thinking queue is empty
5. You have a queue implemented using a list in Python: q = [5, 10, 15]. You want to peek the front element safely without causing an error if the queue is empty. Which code snippet correctly does this?
hard
A. front = q.pop(0)
B. front = q[0] if len(q) > 0 else None
C. front = q[-1]
D. front = q.get()
Solution
Step 1: Check for empty queue before peeking
Accessing q[0] when q is empty causes error, so check length first.
Step 2: Understand other options
pop(0) removes element, not peek; q[-1] accesses last element; q.get() is invalid for list.
Final Answer:
front = q[0] if len(q) > 0 else None -> Option B
Quick Check:
Safe peek with length check [OK]
Hint: Check length before accessing q[0] to avoid errors [OK]
Common Mistakes:
Using pop(0) which removes element
Accessing q[0] without checking empty
Using q.get() on list
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.