Saturday, October 25, 2025
HomeLanguagesPython – PyTorch add() method

Python – PyTorch add() method

PyTorch torch.add() method adds a constant value to each element of the input tensor and returns a new modified tensor.

Syntax: torch.add(inp, c, out=None)

Arguments

  • inp: This is input tensor.
  • c: The value that is to be added to every element of tensor.
  • out: This is optional parameter and it is the output tensor.

Return: It returns a Tensor.

Let’s see this concept with the help of few examples:
Example 1:




# Importing the PyTorch library 
import torch 
    
# A constant tensor of size 6
a = torch.randn(6
print(a) 
    
# Applying the add function and 
# storing the result in 'b' 
b = torch.add(a, 5
print(b)


Output:

0.2403
 1.3826
-0.1763
-1.5177
-0.0555
 1.4558
[torch.FloatTensor of size 6]
 5.2403
 6.3826
 4.8237
 3.4823
 4.9445
 6.4558
[torch.FloatTensor of size 6]

Example 2:




# Importing the PyTorch library 
import torch 
    
# A constant tensor of size 6
a = torch.FloatTensor([1, 3, 8, 4, 10]) 
print(a) 
    
# Applying the add function and 
# storing the result in 'b' 
b = torch.add(a, 5
print(b) 


Output:

 1
  3
  8
  4
 10
[torch.FloatTensor of size 5]
  6
  8
 13
  9
 15
[torch.FloatTensor of size 5]
Last Updated :
26 May, 2020
Like Article
Save Article

<!–

–>

Similar Reads
Related Tutorials
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS