Step 1: Check the shape of axs from plt.subplots(2, 2)
It creates a 2x2 grid, so valid indices are 0 or 1 for rows and columns.
Step 2: Analyze the index axs[2, 0]
Index 2 for rows is out of range (only 0 and 1 allowed), causing IndexError.
Final Answer:
IndexError because axs[2, 0] is out of range -> Option B
Quick Check:
Index out of range = IndexError [OK]
Hint: Check subplot indices start at 0 and max is rows-1 [OK]
Common Mistakes:
Using indices beyond grid size
Confusing syntax error with index error
Assuming axs is a flat list
5. You want to plot 5 different line charts in a single figure using subplots arranged in 2 rows and 3 columns. Which code correctly handles the extra subplot that will remain empty?
hard
A. fig, axs = plt.subplots(2, 3)
for i in range(5):
axs.flat[i].plot([i, i+1, i+2])
axs.flat[5].axis('off')
B. fig, axs = plt.subplots(2, 3)
for i in range(6):
axs[i].plot([i, i+1, i+2])
C. fig, axs = plt.subplots(5, 1)
for i in range(5):
axs[i].plot([i, i+1, i+2])
D. fig, axs = plt.subplots(1, 5)
for i in range(5):
axs[i].plot([i, i+1, i+2])
Solution
Step 1: Understand subplot grid and number of plots
A 2x3 grid has 6 subplots but only 5 are needed, so one remains empty.
Step 2: Use axs.flat to iterate all subplots in 1D
This allows easy indexing over the 2D array of axes.
Step 3: Turn off the extra subplot axis
Calling axs.flat[5].axis('off') hides the unused subplot.
Final Answer:
fig, axs = plt.subplots(2, 3)
for i in range(5):
axs.flat[i].plot([i, i+1, i+2])
axs.flat[5].axis('off') -> Option A
Quick Check:
Use axs.flat and turn off extra subplot [OK]
Hint: Use axs.flat to index subplots and turn off unused ones [OK]
Common Mistakes:
Ignoring extra subplot and leaving it blank
Indexing axs as 1D when it's 2D without flat
Creating wrong grid shape for number of plots
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.