All sample questions / NumPy

What does print(np.concatenate([a, b]).tolist()) print? NumPy Stacking, Splitting and Concatenation

Block 8, Stacking, Splitting and Concatenation, question 20 of the NumPy sample

import numpy as np
a = np.array([1, 2])
b = np.array([3, 4, 5])
print(np.concatenate([a, b]).tolist())

What does this print?

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

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

A. ValueError
Assumes concatenate requires every input to have exactly the same length, the way it requires matching sizes on the other axes for multi dimensional arrays.
B. [3, 4, 5, 1, 2]
Joins the two arrays in the wrong order.
C. [1, 2, 3, 4]
Drops one of the values from the longer array instead of keeping every value from both arrays.
D. [1, 2, 3, 4, 5]
Correct. For 1D arrays, concatenate only needs the arrays to share the same number of dimensions, their lengths along the join axis are free to differ, so two and three values simply add up to five.

The shape rule for concatenate only constrains the axes that are not being joined, the axis being joined is exactly the one allowed to differ in size. For plain 1D arrays there is no other axis to disagree on, so any two 1D arrays can be concatenated regardless of their individual lengths.

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

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

Get the 279 NumPy questions, 9 euros

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

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

Previous question

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