numpy
python
data conversion
dtype
programming

Converting numpy dtypes to native python types

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

NumPy scalar types look similar to Python built-in types, but they are not always interchangeable. That difference becomes obvious when you pass values to JSON encoders, ORMs, web frameworks, or any API that expects plain Python int, float, bool, str, or list.

The fix depends on whether you are converting one scalar or an entire array. The important part is knowing that changing a NumPy dtype is not the same thing as converting to native Python objects.

Convert Individual Scalars with .item()

If you have a NumPy scalar such as np.int64 or np.float32, the cleanest conversion is usually .item().

python
1import numpy as np
2
3count = np.int64(42)
4ratio = np.float32(3.5)
5flag = np.bool_(True)
6
7print(type(count), count.item(), type(count.item()))
8print(type(ratio), ratio.item(), type(ratio.item()))
9print(type(flag), flag.item(), type(flag.item()))

This returns native Python values:

  • 'np.int64 becomes int'
  • 'np.float32 becomes float'
  • 'np.bool_ becomes bool'

You can also call int(value) or float(value) for simple cases, but .item() is a useful general rule for scalar values.

Convert Arrays with .tolist()

For arrays, the usual goal is a nested Python structure. Use .tolist() when you need a Python list made of native values.

python
1import numpy as np
2
3matrix = np.array([[1, 2], [3, 4]], dtype=np.int32)
4as_list = matrix.tolist()
5
6print(as_list)
7print(type(as_list))
8print(type(as_list[0][0]))

That is especially useful before JSON serialization, templating, or returning data from a web API.

python
1import json
2import numpy as np
3
4payload = {
5    "values": np.array([10, 20, 30], dtype=np.int64).tolist()
6}
7
8print(json.dumps(payload))

Without the conversion, many JSON serializers fail because they do not know how to encode NumPy scalar objects.

astype() Changes NumPy Types, Not Python Types

This is the most common source of confusion. astype() converts from one NumPy dtype to another, but the result is still a NumPy array.

python
1import numpy as np
2
3values = np.array([1, 2, 3], dtype=np.int32)
4converted = values.astype(np.float64)
5
6print(converted.dtype)
7print(type(converted))
8print(type(converted[0]))

After astype(np.float64), the array contains NumPy float64 values, not native Python float objects. That is useful for numeric computation, but it does not solve interoperability problems by itself.

Convert Mixed Structures Deliberately

Real data often mixes arrays, scalars, and nested containers. In that case, convert at the boundary where native types are required.

python
1import numpy as np
2
3result = {
4    "mean": np.float64(12.5).item(),
5    "shape": tuple(np.array([2, 3]).tolist()),
6    "scores": np.array([7, 8, 9], dtype=np.int16).tolist(),
7}
8
9print(result)

This boundary-based approach is usually better than converting everything early, because NumPy values are still useful while you are doing numerical work.

It also makes the conversion intent obvious to future readers: native types are needed here because the data is crossing out of the NumPy-heavy part of the program.

Common Pitfalls

The biggest mistake is assuming NumPy scalars are always accepted anywhere a Python built-in would be accepted. Many libraries work fine, but serialization and framework boundaries often expose the difference.

Another common issue is using astype() and expecting native Python objects. It only changes the NumPy dtype.

It is also easy to forget that .tolist() converts the whole array and may allocate a large nested Python object graph. For big arrays, that can be expensive.

Finally, be careful with special dtypes such as datetime64, timedelta64, and structured arrays. They often need format-specific conversion instead of a one-size-fits-all cast.

Summary

  • Use .item() to convert a single NumPy scalar to a native Python value.
  • Use .tolist() to convert arrays into Python lists of native values.
  • 'astype() changes NumPy dtypes, not Python object types.'
  • Convert at integration boundaries such as JSON encoding or API output.
  • Watch out for large arrays and special dtypes that need custom handling.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design