10 print(x[mask]) # 1D tensor of all elements > 10 x_clamped = x.clone() x_clamped[x_clamped > 10] = 0 # zero out values > 10 # ── Fancy (advanced) integer indexing idx = torch.tensor([0, 2]) print(x[:, idx, :]) # shape (2, 2, 4) — select specific indices along dim 1 # ── torch.gather: select elements using an index tensor scores = torch.tensor([[0.1, 0.7, 0.2], [0.3, 0.3, 0.4]]) # (2, 3) top_idx = scores.argmax(dim=1, keepdim=True) # (2, 1) top_val = scores.gather(dim=1, index=top_idx) # (2, 1) print(top_val) # tensor([[0.7], [0.4]]) # ── torch.where: conditional element selection result = torch.where(x > 10, x, torch.zeros_like(x)) # keep if >10, else 0 # ── Important: most slicing returns a VIEW, not a copy! y = x[0] y[0, 0] = 999 print(x[0, 0, 0]) # 999 — x was modified too! (shared memory) # Use x[0].clone() to get an independent copy Indexing patterns Pattern Example Returns Basic slicing x[:, 0] View (shares memory) Boolean mask x[x > 0] Copy (1D, new memory) Fancy indexing x[:, [0,2]] Copy (new memory) Ellipsis x[..., 0] View — skips middle dims gather x.gather(dim, index) Copy — selects per index"> 10 print(x[mask]) # 1D tensor of all elements > 10 x_clamped = x.clone() x_clamped[x_clamped > 10] = 0 # zero out values > 10 # ── Fancy (advanced) integer indexing idx = torch.tensor([0, 2]) print(x[:, idx, :]) # shape (2, 2, 4) — select specific indices along dim 1 # ── torch.gather: select elements using an index tensor scores = torch.tensor([[0.1, 0.7, 0.2], [0.3, 0.3, 0.4]]) # (2, 3) top_idx = scores.argmax(dim=1, keepdim=True) # (2, 1) top_val = scores.gather(dim=1, index=top_idx) # (2, 1) print(top_val) # tensor([[0.7], [0.4]]) # ── torch.where: conditional element selection result = torch.where(x > 10, x, torch.zeros_like(x)) # keep if >10, else 0 # ── Important: most slicing returns a VIEW, not a copy! y = x[0] y[0, 0] = 999 print(x[0, 0, 0]) # 999 — x was modified too! (shared memory) # Use x[0].clone() to get an independent copy Indexing patterns Pattern Example Returns Basic slicing x[:, 0] View (shares memory) Boolean mask x[x > 0] Copy (1D, new memory) Fancy indexing x[:, [0,2]] Copy (new memory) Ellipsis x[..., 0] View — skips middle dims gather x.gather(dim, index) Copy — selects per index" /> 10 print(x[mask]) # 1D tensor of all elements > 10 x_clamped = x.clone() x_clamped[x_clamped > 10] = 0 # zero out values > 10 # ── Fancy (advanced) integer indexing idx = torch.tensor([0, 2]) print(x[:, idx, :]) # shape (2, 2, 4) — select specific indices along dim 1 # ── torch.gather: select elements using an index tensor scores = torch.tensor([[0.1, 0.7, 0.2], [0.3, 0.3, 0.4]]) # (2, 3) top_idx = scores.argmax(dim=1, keepdim=True) # (2, 1) top_val = scores.gather(dim=1, index=top_idx) # (2, 1) print(top_val) # tensor([[0.7], [0.4]]) # ── torch.where: conditional element selection result = torch.where(x > 10, x, torch.zeros_like(x)) # keep if >10, else 0 # ── Important: most slicing returns a VIEW, not a copy! y = x[0] y[0, 0] = 999 print(x[0, 0, 0]) # 999 — x was modified too! (shared memory) # Use x[0].clone() to get an independent copy Indexing patterns Pattern Example Returns Basic slicing x[:, 0] View (shares memory) Boolean mask x[x > 0] Copy (1D, new memory) Fancy indexing x[:, [0,2]] Copy (new memory) Ellipsis x[..., 0] View — skips middle dims gather x.gather(dim, index) Copy — selects per index" />

Prev Next

Python / PyTorch Fundamentals Interview Questions

How does PyTorch handle multi-dimensional indexing and slicing of tensors?

PyTorch tensor indexing follows NumPy-style conventions, including basic slicing, advanced (fancy) indexing with integer/boolean tensors, and the powerful ... (ellipsis) operator for indexing high-dimensional tensors concisely.

import torch

x = torch.arange(24).reshape(2, 3, 4)   # shape (2, 3, 4)

# ── Basic slicing — same as Python lists/NumPy
print(x[0])           # shape (3, 4) — first "batch"
print(x[0, 1])         # shape (4,)  — first batch, second row
print(x[0, 1, 2])      # scalar — single element
print(x[:, 0, :])      # shape (2, 4) — all batches, first row, all cols
print(x[..., 0])       # shape (2, 3) — ellipsis: all leading dims, last dim index 0
print(x[0:1, :, -1])    # shape (1, 3) — slice + negative index

# ── Boolean (mask) indexing
mask = x > 10
print(x[mask])         # 1D tensor of all elements > 10
x_clamped = x.clone()
x_clamped[x_clamped > 10] = 0   # zero out values > 10

# ── Fancy (advanced) integer indexing
idx = torch.tensor([0, 2])
print(x[:, idx, :])    # shape (2, 2, 4) — select specific indices along dim 1

# ── torch.gather: select elements using an index tensor
scores = torch.tensor([[0.1, 0.7, 0.2], [0.3, 0.3, 0.4]])  # (2, 3)
top_idx = scores.argmax(dim=1, keepdim=True)                 # (2, 1)
top_val = scores.gather(dim=1, index=top_idx)                 # (2, 1)
print(top_val)   # tensor([[0.7], [0.4]])

# ── torch.where: conditional element selection
result = torch.where(x > 10, x, torch.zeros_like(x))   # keep if >10, else 0

# ── Important: most slicing returns a VIEW, not a copy!
y = x[0]
y[0, 0] = 999
print(x[0, 0, 0])      # 999 — x was modified too! (shared memory)
# Use x[0].clone() to get an independent copy
Indexing patterns
PatternExampleReturns
Basic slicingx[:, 0]View (shares memory)
Boolean maskx[x > 0]Copy (1D, new memory)
Fancy indexingx[:, [0,2]]Copy (new memory)
Ellipsisx[..., 0]View — skips middle dims
gatherx.gather(dim, index)Copy — selects per index
What happens when you modify a slice obtained via basic indexing, like y = x[0]; y[0] = 999?
What does the ellipsis (...) do in PyTorch tensor indexing like x[..., 0]?

Invest now in Acorns!!! 🚀 Join Acorns and get your $5 bonus!

Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!

Earn passively and while sleeping

Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.

Invest now!!! Get Free equity stock (US, UK only)!

Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.

The Robinhood app makes it easy to trade stocks, crypto and more.


Webull! Receive free stock by signing up using the link: Webull signup.

More Related questions...

What is PyTorch and what are its key advantages over other deep learning frameworks? What is a PyTorch tensor and how does it differ from a NumPy array? What are the most important tensor operations in PyTorch? What are tensor data types (dtypes) in PyTorch and why do they matter? How does broadcasting work in PyTorch and what are the rules? What is autograd in PyTorch and how does it compute gradients? What is the computation graph in PyTorch and how does the dynamic graph differ from a static graph? How do torch.no_grad() and tensor.detach() differ, and when do you use each? What is nn.Module and how do you build a custom neural network in PyTorch? What are nn.Sequential and other container modules in PyTorch? What built-in layers does PyTorch's nn module provide and how do you use the most common ones? What are activation functions in PyTorch and how do you apply them? What are the most important loss functions in PyTorch and when do you use each? What optimizers does PyTorch provide and how do you configure them? What are learning rate schedulers in PyTorch and how do you use them? What are the most common built-in layers in torch.nn and what do they do? How do you initialise weights in a PyTorch model? What loss functions does PyTorch provide and when do you use each? What optimizers does PyTorch provide and how do you choose between them? What are learning rate schedulers in PyTorch and how do you use them? What activation functions are commonly used in PyTorch and how do you choose between them? What loss functions does PyTorch provide and how do you choose the right one? What optimizers does PyTorch provide and what is the difference between SGD, Adam, and AdamW? What is the standard PyTorch training loop and what does each step do? What are Dataset and DataLoader in PyTorch and how do they work together? How do you move tensors and models between CPU and GPU in PyTorch? What is the difference between model.parameters() and model.state_dict() in PyTorch? How do you save and load PyTorch models correctly, including full training checkpoints? What is overfitting and what regularization techniques does PyTorch support to address it? What is the vanishing/exploding gradient problem and how do you detect and fix it in PyTorch? What is weight initialization in PyTorch and why does it matter? What is the difference between nn.Parameter and a regular tensor attribute in nn.Module? How do you implement and use learning rate schedulers in PyTorch? How do you debug a PyTorch training loop where the loss is not decreasing or is NaN? What is the difference between torch.tensor() and torch.Tensor() (capital T) for creating tensors? How does gradient accumulation work in PyTorch and when would you use it? What is mixed precision training in PyTorch and how do you implement it with torch.cuda.amp? What is torch.compile() and how does it speed up PyTorch model execution? What is the difference between batch size, epoch, and iteration in PyTorch training? How do you compute and track evaluation metrics like accuracy during PyTorch training? What is the purpose of torch.manual_seed() and how do you ensure reproducibility in PyTorch? How does PyTorch handle multi-dimensional indexing and slicing of tensors? What is the difference between.view(),.reshape(), and.contiguous() in PyTorch, and why does it matter? How do you freeze layers and perform transfer learning / fine-tuning in PyTorch? What is the purpose of torch.utils.data.random_split() and how do you create train/validation/test splits in PyTorch? What is Batch Normalization in PyTorch and how does it differ from Layer Normalization? How do you implement and use a custom loss function in PyTorch? What is torch.compile() vs TorchScript and how do you export a PyTorch model for production deployment?
Show more question and Answers...

Tools

Comments & Discussions