All sample questions / pandas

What does print(s[s > 3].tolist()) print? pandas Series, Index and dtypes

Block 1, Series, Index and dtypes, question 3 of the pandas sample

import pandas as pd
s = pd.Series([1, 2, 3, 4, 5])
print(s[s > 3].tolist())

What does this print?

  1. A. [4, 5]
  2. B. [3, 4, 5]
  3. C. [True, True]
  4. D. [1, 2, 3]
Show the answer and why each option is right or wrong

Answer, A. [4, 5]

A. [4, 5]
Correct. s > 3 builds a boolean mask that is True only where the value exceeds 3, and indexing the Series with that mask keeps only those matching rows, 4 and 5.
B. [3, 4, 5]
Includes 3 as if the comparison were greater than or equal to 3 rather than strictly greater than.
C. [True, True]
Prints the boolean mask itself instead of the values it selects.
D. [1, 2, 3]
Keeps the rows that fail the condition instead of the ones that pass it.

Indexing a Series with a boolean Series of the same length filters it down to the positions where the mask is True. The comparison itself is strictly greater than, so a value equal to the threshold is excluded, not kept.

The answer above is what pandas 3.0.5 printed when the snippet was run, not what someone expected it to do.

This question comes from a bank of 255 pandas interview questions, all built the same way, sold as one PDF with the full answer key.

Get the 255 pandas questions, 9 euros

Or SQL, Python, pandas and NumPy together, 1,636 questions, 19 euros

Or play the free pandas sample, twenty questions in the browser, also as a free PDF.

Previous question Next question

Did this save you a lookup? Buy me a coffee on Ko-fi.