Python
Tensor
Data Conversion
Multitype Sequence
Machine Learning

Convert python sequence with multiple datatypes to tensor

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

Python lists can mix integers, floats, strings, booleans, and even nested objects in the same sequence. Tensors cannot. A tensor needs a consistent data type, so converting a mixed Python sequence usually means deciding on a common representation first or splitting the data into multiple tensors that preserve the meaning of each field.

Why a Mixed Python Sequence Does Not Convert Cleanly

Python is happy with data like this:

python
data = [1, 2.5, "three", True]

That sequence is valid because a list can hold arbitrary Python objects. Tensor libraries are stricter. A tensor has one dtype for all elements, such as float32, int64, or string. If the values do not fit one coherent dtype, direct conversion will either fail or produce a tensor that is technically valid but not useful.

For example, TensorFlow can only build a sensible numeric tensor if all values are numerically compatible:

python
1import tensorflow as tf
2
3data = [1, 2.5, 3]
4tensor = tf.constant(data, dtype=tf.float32)
5print(tensor)

That works because every value can be represented as a float. Once a string or arbitrary object is mixed in, the conversion question becomes semantic, not merely syntactic.

Normalize to One Type When the Data Is Conceptually Uniform

If the values differ only by Python type but mean the same thing, normalize them before creating the tensor. A list containing int and float values is usually just numeric data, so casting everything to float is appropriate.

python
1import tensorflow as tf
2
3raw_values = [1, 2.5, 3, True]
4normalized = [float(value) for value in raw_values]
5
6tensor = tf.constant(normalized, dtype=tf.float32)
7print(tensor)

This works because True becomes 1.0, and every element now fits the same numeric dtype. Whether that is correct depends on the business meaning of the data. If True was a category rather than a numeric signal, this conversion would be misleading.

You can do the same kind of cleanup with NumPy before creating a tensor:

python
1import numpy as np
2import tensorflow as tf
3
4values = np.asarray([1, 2.5, 3], dtype=np.float32)
5tensor = tf.convert_to_tensor(values)
6print(tensor.dtype)

That pattern is useful when your preprocessing logic already lives in NumPy.

Split Heterogeneous Records into Separate Tensors

In machine learning code, a mixed Python sequence often means the original data is structured and should not become one tensor at all. Suppose each record contains a numeric age, a floating-point income, and a city name:

python
1records = [
2    {"age": 30, "income": 55000.0, "city": "Toronto"},
3    {"age": 42, "income": 72000.0, "city": "Montreal"},
4]

Trying to force each record into one tensor loses information. The better representation is one tensor per homogeneous field:

python
1import tensorflow as tf
2
3ages = tf.constant([row["age"] for row in records], dtype=tf.int32)
4incomes = tf.constant([row["income"] for row in records], dtype=tf.float32)
5cities = tf.constant([row["city"] for row in records], dtype=tf.string)
6
7features = {
8    "age": ages,
9    "income": incomes,
10    "city": cities,
11}
12
13print(features)

This preserves meaning. Numeric features stay numeric, and text stays text until you deliberately encode it.

If text needs to become model input, encode it explicitly instead of relying on accidental coercion:

python
1import tensorflow as tf
2
3cities = tf.constant(["Toronto", "Montreal", "Toronto"])
4lookup = tf.keras.layers.StringLookup()
5lookup.adapt(cities)
6
7encoded_cities = lookup(cities)
8print(encoded_cities)

Avoid Object-Like Tensors as a Shortcut

Some libraries can represent mixed Python objects through object-based arrays or structures, but that is usually not the right end state for tensor computation. The fact that conversion succeeds does not mean the resulting object is useful for training, vectorized math, or model serving.

A good rule is simple: ask what operation you want to perform after conversion. If the answer is numeric computation, every element should have a numeric meaning and a clear shared dtype. If the answer is feature processing, structured tensors or a dictionary of tensors is usually better than one mixed sequence.

Common Pitfalls

The biggest mistake is assuming that because Python allows mixed lists, tensor libraries should accept them the same way. Python container flexibility and tensor semantics are different design choices.

Another mistake is converting everything to strings just to make the error go away. That creates a tensor, but it usually destroys the numeric meaning the model actually needs.

Developers also sometimes collapse structured records into one sequence when the real answer is multiple tensors, each tied to one field. This becomes especially important once preprocessing, batching, or feature columns enter the picture.

Finally, be careful with automatic coercion. A conversion that silently promotes values may still be wrong for the domain. Always decide on dtype based on meaning, not just on what the library will accept.

Summary

  • A tensor needs one coherent dtype, while Python sequences can mix unrelated types freely.
  • If values are conceptually the same kind of data, normalize them before conversion.
  • Structured heterogeneous records are usually better represented as multiple tensors.
  • Text and categorical values often need explicit encoding before model use.
  • A successful conversion is useful only when the resulting tensor still matches the meaning of the original data.

Related reading
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
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

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