Imagine have n tensors. If we stay in 3D, those correspond to volumes, namely rectangular cuboids. Stacking corresponds to combining those n volumes on an additional dimension: here a 4th dimension is added to host the n 3D volumes. This operation is in clear contrast with concatenation, where the volumes would be combined on one of the existing dimensions. So concatenation of three-dimensional tensors would result in a 3D tensor.

Here is a possible representation of the stacking operations for limited dimensions sizes (up to three-dimensional inputs):

Where you chose to perform the stacking defines along which new dimension the stack will take place. In the above examples, the newly created dimension is last, hence the idea of "added dimension" makes more sense.

In the following visualization, we observe how tensors can be stacked on different axes. This in turn affects the resulting tensor shape

  • For the 1D case, for instance, it can also happen on the first axis, see below:

    With code:

    >>> x_1d = list(torch.empty(3, 2))     # 3 lines
    
    >>> torch.stack(x_1d, 0).shape         # axis=0 stacking
    torch.Size([3, 2])
    
    >>> torch.stack(x_1d, 1).shape         # axis=1 stacking
    torch.Size([2, 3])
    
  • Similarly for two-dimensional inputs:

    With code:

    >>> x_2d = list(torch.empty(3, 2, 2))   # 3 2x2-squares
    
    >>> torch.stack(x_2d, 0).shape          # axis=0 stacking
    torch.Size([3, 2, 2])
    
    >>> torch.stack(x_2d, 1).shape          # axis=1 stacking
    torch.Size([2, 3, 2])
    
    >>> torch.stack(x_2d, 2).shape          # axis=2 stacking
    torch.Size([2, 2, 3])
    

With this state of mind, you can intuitively extend the operation to n-dimensional tensors.

Answer from Ivan on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-pytorch-stack-method
Python PyTorch stack() method - GeeksforGeeks
February 28, 2022 - PyTorch torch.stack() method joins (concatenates) a sequence of tensors (two or more tensors) along a new dimension. It inserts new dimension and concatenates the tensors along that dimension.
🌐
Medium
medium.com › @garybao › understanding-torch-stack-in-pytorch-when-to-use-and-when-not-to-af3ce8711967
Understanding torch.stack() in PyTorch: When to Use and When Not To | by Gary Bao | Medium
June 24, 2025 - torch.stack() takes a sequence (list or tuple) of tensors and concatenates them along a new dimension, creating a higher-dimensional tensor.
🌐
APXML
apxml.com › courses › getting-started-with-pytorch › chapter-2-advanced-tensor-manipulations › joining-splitting-tensors
Join & Split PyTorch Tensors | Cat, Stack, Chunk
torch.stack, PyTorch Documentation, 2024 (PyTorch Foundation) - Official documentation describing torch.stack, used for stacking tensors along a new dimension.
🌐
DEV Community
dev.to › hyperkai › stack-in-pytorch-1bp1
stack in PyTorch - DEV Community
November 5, 2024 - stack() can get the 1D or more D stacked tensor of zero or more elements from the one or more 0D or more D tensors of zero or more elements as shown below: ... The 1st argument with torch is tensors(Required-Type:tuple or list of tensor of int, ...
Top answer
1 of 3
20

Imagine have n tensors. If we stay in 3D, those correspond to volumes, namely rectangular cuboids. Stacking corresponds to combining those n volumes on an additional dimension: here a 4th dimension is added to host the n 3D volumes. This operation is in clear contrast with concatenation, where the volumes would be combined on one of the existing dimensions. So concatenation of three-dimensional tensors would result in a 3D tensor.

Here is a possible representation of the stacking operations for limited dimensions sizes (up to three-dimensional inputs):

Where you chose to perform the stacking defines along which new dimension the stack will take place. In the above examples, the newly created dimension is last, hence the idea of "added dimension" makes more sense.

In the following visualization, we observe how tensors can be stacked on different axes. This in turn affects the resulting tensor shape

  • For the 1D case, for instance, it can also happen on the first axis, see below:

    With code:

    >>> x_1d = list(torch.empty(3, 2))     # 3 lines
    
    >>> torch.stack(x_1d, 0).shape         # axis=0 stacking
    torch.Size([3, 2])
    
    >>> torch.stack(x_1d, 1).shape         # axis=1 stacking
    torch.Size([2, 3])
    
  • Similarly for two-dimensional inputs:

    With code:

    >>> x_2d = list(torch.empty(3, 2, 2))   # 3 2x2-squares
    
    >>> torch.stack(x_2d, 0).shape          # axis=0 stacking
    torch.Size([3, 2, 2])
    
    >>> torch.stack(x_2d, 1).shape          # axis=1 stacking
    torch.Size([2, 3, 2])
    
    >>> torch.stack(x_2d, 2).shape          # axis=2 stacking
    torch.Size([2, 2, 3])
    

With this state of mind, you can intuitively extend the operation to n-dimensional tensors.

2 of 3
3

Very simple! I will use 4 varibles for this example. The function torch.stack is very similar to numpy (vstack and hstack). Example :

t1 = torch.tensor([1,2,3])
t2 = torch.tensor([4,5,6])
t3 = torch.tensor([7,8,9])
t4 = torch.tensor([10,11,12])

if you try this cmd

>> torch.stack((t1,t2,t3,t4),dim=1).size()
>> torch.Size([3, 4])

if you change dim=1 with dim=0

>> torch.stack((t1,t2,t3,t4),dim=0).size()
>> torch.Size([4, 3])

In first case you have a tensor with 3x4 dimensional but in last case you have a 4x3 tensor. Test this code without using .size() !

>> torch.stack((t1,t2,t3,t4),dim=1)
>> tensor([[ 1,  4,  7, 10],
        [ 2,  5,  8, 11],
        [ 3,  6,  9, 12]])

>> torch.stack((t1,t2,t3,t4),dim=0)
>> tensor([[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9],
        [10, 11, 12]])

Happy Coding!

🌐
Medium
medium.com › data-scientists-diary › pytorchs-stack-method-a-practical-guide-for-data-scientists-2af8088f40a5
PyTorch’s stack() Method: A Practical Guide for Data Scientists
January 19, 2025 - Rather than iterating over individual data points, you can use stack() to assemble your data into batches. ... import torch # Imagine we have a batch of 4 grayscale images, each 28x28 image1 = torch.rand(28, 28) image2 = torch.rand(28, 28) image3 ...
🌐
Python Guides
pythonguides.com › pytorch-stack
How to Use PyTorch Stack?
June 19, 2025 - Here’s how I handle dynamic stacking: # Simulating a variable number of features extracted from data feature_list = [] num_samples = 5 # Could vary based on available data # Generate and collect features for i in range(num_samples): # In a real scenario, this might be feature extraction from different data points feature = torch.randn(128) # 128-dimensional feature vector feature_list.append(feature) # Stack all features at once feature_batch = torch.stack(feature_list) print(f"Feature batch shape: {feature_batch.shape}") # torch.Size([5, 128])
Find elsewhere
🌐
Codecademy
codecademy.com › docs › pytorch › tensor operations › .stack()
PyTorch | Tensor Operations | .stack() | Codecademy
November 20, 2024 - In PyTorch, the .stack() method stacks given tensors along a specified dimension to create a combined tensor.
🌐
ProgramCreek
programcreek.com › python › example › 101135 › torch.stack
Python Examples of torch.stack
def find_max_triples(p1, p2, topN=5, prob_thd=None): """ Find a list of (k1, k2) where k1 >= k2 with the maximum values of p1[k1] * p2[k2] Args: p1 (torch.CudaTensor): (N, L) batched start_idx probabilities p2 (torch.CudaTensor): (N, L) batched end_idx probabilities topN (int): return topN pairs with highest values prob_thd (float): Returns: batched_sorted_triple: N * [(st_idx, ed_idx, confidence), ...] """ product = torch.bmm(p1.unsqueeze(2), p2.unsqueeze(1)) # (N, L, L), end_idx >= start_idx upper_product = torch.stack([torch.triu(p) for p in product] ).data.cpu().numpy() # (N, L, L) the lower part becomes zeros batched_sorted_triple = [] for idx, e in enumerate(upper_product): sorted_triple = topN_array_2d(e, topN=topN) if prob_thd is not None: sorted_triple = [t for t in sorted_triple if t[2] >= prob_thd] batched_sorted_triple.append(sorted_triple) return batched_sorted_triple
🌐
YouTube
youtube.com › codecraze
pytorch stack tensors - YouTube
Download this code from https://codegive.com In PyTorch, the torch.stack() function is a powerful tool for combining multiple tensors along a new dimension. ...
Published: January 6, 2024
Views: 11
🌐
GitHub
alband.github.io › doc_view › generated › torch.stack.html
torch.stack — PyTorch master documentation
torch.stack · Shortcuts · torch.stack(tensors, dim=0, *, out=None) → Tensor¶ · Concatenates a sequence of tensors along a new dimension. All tensors need to be of the same size. Parameters · tensors (sequence of Tensors) – sequence of tensors to concatenate ·
🌐
YouTube
youtube.com › watch
Stack vs Concat in PyTorch, TensorFlow & NumPy - Deep Learning Tensor Ops - YouTube
Welcome to this neural network programming series. In this episode, we will dissect the difference between concatenating and stacking tensors together. We'll...
Published: July 18, 2019
🌐
Whytorch
whytorch.org › torch.stack
torch.stack | WhyTorch
torch.stack · ans = torch.stack([tensor0, tensor1, ...], dim) tensor0 · tensor1 · dim · ans · Click/tap any element to explain it · stack joins a sequence of tensors along a new dimension dim. All tensors must have the same shape.