Bird
Raised Fist0
NumPydata~20 mins

Type promotion in operations in NumPy - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Type Promotion Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of adding int32 and float64 arrays
What is the data type of the resulting array after adding these two NumPy arrays?
NumPy
import numpy as np
arr1 = np.array([1, 2, 3], dtype=np.int32)
arr2 = np.array([1.5, 2.5, 3.5], dtype=np.float64)
result = arr1 + arr2
print(result.dtype)
Afloat64
Bint32
Cfloat32
Dobject
Attempts:
2 left
💡 Hint
When adding integers and floats, NumPy promotes to the more general type.
❓ Predict Output
intermediate
2:00remaining
Result type of multiplying uint8 and int16 arrays
What is the data type of the resulting array after multiplying these two NumPy arrays?
NumPy
import numpy as np
arr1 = np.array([10, 20, 30], dtype=np.uint8)
arr2 = np.array([1000, 2000, 3000], dtype=np.int16)
result = arr1 * arr2
print(result.dtype)
Aint16
Bint32
Cuint8
Dfloat64
Attempts:
2 left
💡 Hint
NumPy promotes the narrower dtype to the wider one.
❓ data_output
advanced
2:30remaining
Output array and dtype after adding complex64 and float32 arrays
What is the output array and its data type after adding these two arrays?
NumPy
import numpy as np
arr1 = np.array([1+2j, 3+4j], dtype=np.complex64)
arr2 = np.array([1.5, 2.5], dtype=np.float32)
result = arr1 + arr2
print(result)
print(result.dtype)
A[2.5+2.j 5.5+4.j] with dtype float64
B[2.5+2.j 5.5+4.j] with dtype complex128
C[2.5 5.5] with dtype float32
D[2.5+2.j 5.5+4.j] with dtype complex64
Attempts:
2 left
💡 Hint
Adding float32 to complex64 promotes float32 to complex64.
❓ Predict Output
advanced
2:00remaining
Data type after subtracting int64 and uint64 arrays
What is the data type of the resulting array after subtracting these two arrays?
NumPy
import numpy as np
arr1 = np.array([10, 20, 30], dtype=np.int64)
arr2 = np.array([1, 2, 3], dtype=np.uint64)
result = arr1 - arr2
print(result.dtype)
Afloat64
Bint64
Cuint64
Dobject
Attempts:
2 left
💡 Hint
Subtracting signed and unsigned 64-bit integers promotes to float64 to avoid overflow.
❓ visualization
expert
3:00remaining
Visualizing type promotion in mixed dtype operations
Which option shows the correct plot of the data types resulting from adding arrays of these dtypes: int8, uint16, float32, complex128?
NumPy
import numpy as np
import matplotlib.pyplot as plt

dtypes = [np.int8, np.uint16, np.float32, np.complex128]
results = []
for i, dt1 in enumerate(dtypes):
    for j, dt2 in enumerate(dtypes):
        a = np.array([1], dtype=dt1)
        b = np.array([1], dtype=dt2)
        c = a + b
        results.append((dt1.__name__, dt2.__name__, c.dtype.name))

# Prepare data for heatmap
import pandas as pd
pivot_data = pd.DataFrame(results, columns=['Type1', 'Type2', 'Result'])
pivot_table = pivot_data.pivot('Type1', 'Type2', 'Result')

plt.figure(figsize=(8,6))
plt.title('Resulting dtype from adding two dtypes')
plt.imshow(pivot_table.applymap(lambda x: {'int8':0,'uint16':1,'float32':2,'complex128':3}[x]), cmap='viridis')
plt.xticks(range(len(dtypes)), [dt.__name__ for dt in dtypes])
plt.yticks(range(len(dtypes)), [dt.__name__ for dt in dtypes])
plt.colorbar(ticks=[0,1,2,3], label='dtype code')
plt.show()
AA heatmap where adding int8 and uint16 results in int8, and adding float32 and complex128 results in float32
BA heatmap where adding int8 and uint16 results in complex128, and adding float32 and complex128 results in uint16
CA heatmap where adding int8 and uint16 results in uint16, and adding float32 and complex128 results in complex128
DA heatmap where all additions result in float64 regardless of input types
Attempts:
2 left
💡 Hint
NumPy promotes to the smallest dtype that can hold both inputs without loss.

Practice

(1/5)
1. What happens in NumPy when you add an integer array to a float array?
easy
A. The result array will have integer type, truncating floats.
B. The result array will have float type due to type promotion.
C. NumPy throws a type error and stops execution.
D. The result array will have string type.

Solution

  1. Step 1: Understand type promotion in mixed operations

    When adding int and float arrays, NumPy promotes the int to float to avoid losing decimal information.
  2. Step 2: Check the resulting data type

    The output array will have float dtype because float has higher precision than int.
  3. Final Answer:

    The result array will have float type due to type promotion. -> Option B
  4. Quick Check:

    int + float = float [OK]
Hint: Mixed int and float always promote to float [OK]
Common Mistakes:
  • Assuming result stays integer and truncates decimals
  • Thinking NumPy throws an error on mixed types
  • Believing result becomes string type
2. Which of the following NumPy operations correctly promotes types when multiplying an int array by a float scalar?
easy
A. np.array([1, 2, 3]) * 2.0
B. np.array([1, 2, 3]) * '2'
C. np.array([1, 2, 3]) * 2
D. np.array([1, 2, 3]) * np.array(['2', '3', '4'])

Solution

  1. Step 1: Identify valid type promotion in multiplication

    Multiplying an int array by a float scalar promotes the result to float.
  2. Step 2: Check each option for correct type promotion

    np.array([1, 2, 3]) * 2.0 multiplies by 2.0 (float), so result is float array. np.array([1, 2, 3]) * 2 multiplies by int 2, no promotion. The options involving strings cause errors.
  3. Final Answer:

    np.array([1, 2, 3]) * 2.0 -> Option A
  4. Quick Check:

    int array * float scalar = float array [OK]
Hint: Multiply int array by float scalar for float result [OK]
Common Mistakes:
  • Using string instead of numeric scalar
  • Expecting int result when multiplying by float
  • Confusing string multiplication with numeric
3. What is the dtype of the result when you run this code?
import numpy as np
arr1 = np.array([1, 2, 3], dtype=np.int32)
arr2 = np.array([1.5, 2.5, 3.5], dtype=np.float64)
result = arr1 + arr2
dtype_result = result.dtype
medium
A. int32
B. object
C. float32
D. float64

Solution

  1. Step 1: Identify input array dtypes

    arr1 is int32, arr2 is float64.
  2. Step 2: Understand type promotion rules

    When adding int32 and float64, NumPy promotes to float64 to preserve precision.
  3. Final Answer:

    float64 -> Option D
  4. Quick Check:

    int32 + float64 = float64 [OK]
Hint: Higher precision float wins in mixed int-float ops [OK]
Common Mistakes:
  • Assuming result is int32
  • Confusing float32 with float64
  • Expecting object dtype for numeric arrays
4. Consider this code snippet:
import numpy as np
arr = np.array([1, 2, 3], dtype=np.int8)
result = arr + 1.5

Why might the result's dtype not be what you expect if you change arr to np.int16?
medium
A. Because int16 promotes to string, causing unexpected dtype.
B. Because int16 does not promote and causes an error.
C. Because int16 promotes to float64, changing result dtype.
D. Because int16 promotes to int8, lowering precision.

Solution

  1. Step 1: Understand type promotion with int8 and int16

    Adding float 1.5 to int8 promotes to float64. Similarly, int16 also promotes to float64.
  2. Step 2: Explain why dtype changes with int16

    int16 has higher precision than int8 but still promotes to float64 when added to float, so result dtype is float64, not int16.
  3. Final Answer:

    Because int16 promotes to float64, changing result dtype. -> Option C
  4. Quick Check:

    int16 + float = float64 [OK]
Hint: Adding float promotes int16 to float64, not int16 [OK]
Common Mistakes:
  • Thinking int16 causes error with float addition
  • Assuming int16 promotes down to int8
  • Believing result becomes string dtype
5. You have two arrays:
arr_int = np.array([1000, 2000], dtype=np.int16)
arr_float = np.array([0.1, 0.2], dtype=np.float32)

You want to add them and keep the result as float32 to save memory. Which code correctly achieves this with type promotion?
hard
A. result = arr_int.astype(np.float32) + arr_float
B. result = arr_int + arr_float.astype(np.float64)
C. result = arr_int + arr_float
D. result = arr_int.astype(np.int32) + arr_float

Solution

  1. Step 1: Understand default type promotion

    Adding int16 and float32 promotes to float64 by default, increasing memory.
  2. Step 2: Convert int16 to float32 before addition

    By converting arr_int to float32, adding float32 arrays keeps result as float32, saving memory.
  3. Step 3: Check other options

    result = arr_int + arr_float.astype(np.float64) promotes to float64, increasing memory. result = arr_int + arr_float promotes to float64 by default. result = arr_int.astype(np.int32) + arr_float promotes int16 to int32, then adds float32, promoting to float64.
  4. Final Answer:

    result = arr_int.astype(np.float32) + arr_float -> Option A
  5. Quick Check:

    Cast int to float32 first to keep float32 result [OK]
Hint: Cast int to float32 before adding float32 to keep dtype [OK]
Common Mistakes:
  • Ignoring default promotion to float64
  • Casting float to float64 increasing memory
  • Not casting int before addition
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard