# How to concatenate list of pytorch tensors?

Suppose I have a list tensors in the same size. Is there any unified function to merge all these like `np.array(array_list)` in case you have list or numpy arrays.

This is my current solution

`````` data = th.zeros([len(imgs), imgs.size(), imgs.size(), imgs.size()])
for i, img in enumerate(imgs):
print(img.size())
print(img.type())
data[i] = img``````
1 Like

You can use `torch.cat` or `torch.stack`

26 Likes

just in case you were wondering about the difference:

`stack`

Concatenates sequence of tensors along a new dimension.

`cat`

Concatenates the given sequence of seq tensors in the given dimension.

So if `A` and `B` are of shape (3, 4), `torch.cat([A, B], dim=0)` will be of shape (6, 4) and `torch.stack([A, B], dim=0)` will be of shape (2, 3, 4).

18 Likes

What if A is of shape (1,3,4) and B is (3,4)?

I want the result to be (2,3,4). How do I do this?

``````a = torch.rand(1, 3, 4)
print(a.shape)
b = torch.rand(3, 4)
print(b.shape)
b = b.unsqueeze(0)
print(b.shape)
c = torch.cat([a, b], dim=0)
print(c.shape)
``````
3 Likes

Thank you, it works.