Bird
0
0

You have a list of lists with varying lengths: [[1, 2], [3, 4, 5], [6]]. How can you create a NumPy array that holds this data without error?

hard📝 Application Q8 of 15
NumPy - Creating Arrays
You have a list of lists with varying lengths: [[1, 2], [3, 4, 5], [6]]. How can you create a NumPy array that holds this data without error?
AUse <code>np.array(data)</code> directly without dtype
BUse <code>np.array(data, dtype=object)</code> to allow varying lengths
CPad inner lists to equal length before using <code>np.array()</code>
DConvert the list to a Python tuple before passing to <code>np.array()</code>
Step-by-Step Solution
Solution:
  1. Step 1: Understand ragged arrays in NumPy

    NumPy cannot create regular arrays from lists with different inner lengths unless dtype=object is used.
  2. Step 2: Use dtype=object to allow ragged arrays

    Setting dtype=object tells NumPy to store references to Python objects, allowing varying lengths.
  3. Final Answer:

    Use np.array(data, dtype=object) to allow varying lengths -> Option B
  4. Quick Check:

    dtype=object allows ragged arrays [OK]
Quick Trick: Use dtype=object for ragged arrays [OK]
Common Mistakes:
  • Ignoring dtype=object for ragged data
  • Expecting np.array to auto-handle ragged lists
  • Padding lists unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes