# Difference Among Scalar, Tuple and List When Creating PyTorch Tensor – PyTorch Tutorial

By | November 25, 2022

When we are creating pytorch tensor, we may use scalar, tuple and list. In this tutorial, we will introduce the difference when using them.

## Create a pytorch tensor

There are some methods to create pytorch tensor. For example:

Simple Guide to Create a Tensor in PyTorch – PyTorch Tutorial

## The difference when creating tensor by scalar, tuple and python list

We will use an example to show the difference.

For example:

import torch
import numpy as np
# create a tensor by scalar
x = torch.LongTensor(5)
# create a tensor by tuple
y = torch.LongTensor((3,2))
#create a tensor by list
z1 = torch.LongTensor([1, 2, 3,4])
z2 = torch.LongTensor([5])
print(x, y, z1, z2)

Run this code, we will see:

tensor([0, 0, 0, 0, 0]) tensor([3, 2]) tensor([1, 2, 3, 4]) tensor([5])

From this result, we can find:

## 1. scalar for tensor

5 is a scalar, torch.LongTensor(5) will create a vector that contains 5 elements.

tensor([0, 0, 0, 0, 0])

We should notice: torch.LongTensor(5) does not create a tensor with the element value 5. It creates a vector.

Moreover, if you plan to create a tensor with much dimensions, you can do as follows:

print(torch.FloatTensor(3,2))

Then, you can create a 3*2 tensor.

tensor([[0., 0.],
[0., 0.],
[0., 0.]])

## 2. tuple for tensor

In this example: (3,2) is a python tuple, torch.LongTensor((3,2)) will create a tensor with the element [3, 2]

We should notice: torch.LongTensor((3,2)) does not create a tensor with the shape 3*2

## 3. list for tensor

Similar to tuple, it also create a tensor that the element is python list.

For example:

z1 = torch.LongTensor([1, 2, 3,4])
z2 = torch.LongTensor([5])

The value is:

tensor([1, 2, 3, 4]) tensor([5])