Use PyTorch's To List (tolist) operation to convert a PyTorch Tensor to a Python list

Use PyTorch's To List (tolist) operation to convert a PyTorch Tensor to a Python list

This video will show you how to use PyTorch’s to list operation to convert a PyTorch tensor to a Python list.

First, we import PyTorch.

```
import torch
```

Then we check what version of PyTorch we are using.

```
print(torch.__version__)
```

We are using PyTorch 0.4.1.

Next, let’s create the example tensor we will be converting into a Python list.

We will use the PyTorch ones operation to create a tensor that’s 2x3x4 full of floating point ones.

```
pytorch_tensor_example = torch.ones(2, 3, 4)
```

So torch.ones, and the structure’s going to have 2x3x4 dimensions, and we’re going to assign it to the Python variable pytorch_tensor_example.

Now, let’s print our pytorch_tensor_example Python variable to see what’s inside.

```
print(pytorch_tensor_example)
```

We see that it’s a PyTorch tensor, we see that its structure is 2x3x4, each element is a 1, and each element is followed by a decimal point which denotes that it is a floating point number.

Just to double check, let’s use Python’s type operation to check the type of the tensor.

```
type(pytorch_tensor_example)
```

And we see that it is a torch.Tensor.

Now that we have the tensor, let’s use the to list operation to convert our PyTorch tensor to a Python list.

So we have our tensor and we’re going to use PyTorch’s .tolist operation.

```
pytorch_tensor_as_list = pytorch_tensor_example.tolist()
```

The result of this operation is going to be assigned to the Python variable, pytorch_tensor_as_list.

Now that we have the list, let’s print it to see the results.

```
print(pytorch_tensor_as_list)
```

We see that it is a nested list.

The outside list contains two elements.

Here is the first one.

Here is the second one.

Each of these lists contains three elements – one, two, and three.

One, two, and three.

And each of those internal lists contains four elements.

So 2x3x4.

Next, let’s double check what this thing actually is by using the Python type operation again.

```
type(pytorch_tensor_as_list)
```

So we have type, and then we’re passing our pytorch_tensor_as_list variable, and we see that it is a Python list.

Perfect - We were able to use PyTorch’s to list operation to convert a PyTorch tensor to a Python list.

Receive the Data Science Weekly Newsletter every Thursday

Easy to unsubscribe at any time. Your e-mail address is safe.