Bird
0
0

You have a 2D array of zeros with shape (3, 3). How can you create a new array of the same shape filled with ones using np.ones_like()?

hard📝 Application Q9 of 15
NumPy - Creating Arrays
You have a 2D array of zeros with shape (3, 3). How can you create a new array of the same shape filled with ones using np.ones_like()?
Anp.ones_like(np.zeros((3, 3)))
Bnp.ones(np.zeros((3, 3)))
Cnp.ones((3, 3))
Dnp.ones_like((3, 3))
Step-by-Step Solution
Solution:
  1. Step 1: Understand np.ones_like()

    This function creates an array of ones with the same shape and dtype as the input array.
  2. Step 2: Check each option

    np.ones_like(np.zeros((3, 3))) correctly passes a zeros array to np.ones_like(), creating a ones array of same shape. np.ones(np.zeros((3, 3))) passes an array to np.ones(), which expects shape, causing error. np.ones((3, 3)) creates a new array but not based on existing array. np.ones_like((3, 3)) passes a tuple, invalid for np.ones_like().
  3. Final Answer:

    np.ones_like(np.zeros((3, 3))) -> Option A
  4. Quick Check:

    np.ones_like() copies shape and dtype from input array [OK]
Quick Trick: Use np.ones_like() to match shape and dtype of existing array [OK]
Common Mistakes:
  • Passing shape instead of array to np.ones_like()
  • Using np.ones() with array argument
  • Confusing np.ones_like() with np.ones()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes