PyTorch .logical_not()
Anonymous contributor
Published Oct 29, 2025
Contribute to Docs
In PyTorch, the .logical_not() function performs an element-wise logical negation on a tensor. It returns a tensor where each element is True if the corresponding input is False, and False otherwise. For non-boolean tensors, zeros are treated as False and non-zeros as True.
This function is commonly used in masking, boolean indexing, and creating complement conditions.
Syntax
torch.logical_not(input, *, out=None)
Parameters:
input: The input tensor containing boolean or numeric values.out(Optional): A tensor to store the result. It must have the same shape as the output. The dtype is typicallytorch.bool, but integer types that can represent0and1(liketorch.int16) are also supported. The results are stored as1forTrueand0forFalse.
Return value:
Returns a new tensor containing the element-wise logical negation of the input tensor.
Example
The following example demonstrates the use of .logical_not() for masking and boolean inversion:
import torch# Create a boolean tensormask = torch.tensor([True, False, True, False])# Element-wise logical NOTinv = torch.logical_not(mask)print('mask:', mask)print('logical_not(mask):', inv)# Use logical_not to invert a condition from a numeric tensorvals = torch.tensor([0.0, 1.5, -2.0, 0.0])cond = vals > 0cond_inv = torch.logical_not(cond)print('\nvals:', vals)print('cond (vals > 0):', cond)print('cond inverted with logical_not:', cond_inv)# Numeric input — zeros are False, non-zeros are Trueprint(torch.logical_not(torch.tensor([0., 2.45, -20., 3.8], dtype=torch.double)))# Using an integer out tensor (int16) to store 0/1 resultsout_buf = torch.empty(4, dtype=torch.int16)print(torch.logical_not(torch.tensor([0., 2.45, -20., 3.8], dtype=torch.double), out=out_buf))
The above code produces the following output:
mask: tensor([ True, False, True, False])logical_not(mask): tensor([False, True, False, True])vals: tensor([ 0.0000, 1.5000, -2.0000, 0.0000])cond (vals > 0): tensor([False, True, False, False])cond inverted with logical_not: tensor([ True, False, True, True])tensor([ True, False, False, False])tensor([1, 0, 0, 0], dtype=torch.int16)
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PyTorch on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn how to use PyTorch to build, train, and test artificial neural networks in this course.
- Intermediate.3 hours