Bird
Raised Fist0
PyTorchml~20 mins

__getitem__ and __len__ in PyTorch - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Dataset Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of __getitem__ in a PyTorch Dataset
Consider this PyTorch Dataset class. What will be the output of dataset[2]?
PyTorch
import torch
from torch.utils.data import Dataset

class SimpleDataset(Dataset):
    def __init__(self):
        self.data = [10, 20, 30, 40, 50]
    def __len__(self):
        return len(self.data)
    def __getitem__(self, idx):
        return self.data[idx] * 2

dataset = SimpleDataset()
output = dataset[2]
A30
B60
C40
DIndexError
Attempts:
2 left
💡 Hint
Remember __getitem__ returns data at index multiplied by 2.
❓ Model Choice
intermediate
2:00remaining
Choosing __len__ for a Custom Dataset
You have a dataset class with a list of 1000 images. Which implementation of __len__ correctly returns the dataset size?
A
def __len__(self):
    return 1000
B
def __len__(self):
    return self.images[0]
C
def __len__(self):
    return len(self.images)
D
def __len__(self):
    return self.images
Attempts:
2 left
💡 Hint
The length should reflect the number of items in the images list.
🔧 Debug
advanced
2:00remaining
Debugging __getitem__ Index Error
This Dataset class raises an IndexError when accessing dataset[5]. Why?
PyTorch
class MyDataset:
    def __init__(self):
        self.data = [1, 2, 3, 4, 5]
    def __len__(self):
        return len(self.data)
    def __getitem__(self, idx):
        return self.data[idx + 1]

dataset = MyDataset()
output = dataset[5]
ABecause data list is empty
BBecause __len__ returns wrong length
CBecause __getitem__ returns a list instead of a number
DBecause __getitem__ accesses index 6 which is out of range
Attempts:
2 left
💡 Hint
Check how the index is used inside __getitem__.
❓ Hyperparameter
advanced
2:00remaining
Effect of __len__ on DataLoader Batching
If a Dataset's __len__ returns 50 but actually contains 100 samples, what happens when using a DataLoader with batch size 10?
ADataLoader will load only 50 samples in 5 batches
BDataLoader will load all 100 samples in 10 batches
CDataLoader will raise a ValueError due to mismatch
DDataLoader will load 100 samples but batch size will be ignored
Attempts:
2 left
💡 Hint
DataLoader uses __len__ to know dataset size.
🧠 Conceptual
expert
2:00remaining
Why Implement Both __getitem__ and __len__ in PyTorch Dataset?
Why is it important to implement both __getitem__ and __len__ methods in a PyTorch Dataset class?
ABecause DataLoader uses __len__ to know dataset size and __getitem__ to fetch samples by index
BBecause __getitem__ initializes the dataset and __len__ trains the model
CBecause __len__ loads data and __getitem__ shuffles it
DBecause __len__ is used only for printing and __getitem__ is optional
Attempts:
2 left
💡 Hint
Think about how DataLoader interacts with Dataset.

Practice

(1/5)
1. What does the __len__ method do in a PyTorch dataset class?
easy
A. It saves the dataset to disk.
B. It returns one data item by index.
C. It returns the total number of items in the dataset.
D. It trains the model on the dataset.

Solution

  1. Step 1: Understand the role of __len__ in datasets

    The __len__ method tells PyTorch how many items are in the dataset so it knows the dataset size.
  2. Step 2: Differentiate from __getitem__

    Unlike __getitem__ which returns one item, __len__ returns the total count of items.
  3. Final Answer:

    It returns the total number of items in the dataset. -> Option C
  4. Quick Check:

    __len__ = total items [OK]
Hint: Remember: length means total count, not single item [OK]
Common Mistakes:
  • Confusing __len__ with __getitem__
  • Thinking __len__ returns data samples
  • Assuming __len__ trains the model
2. Which of the following is the correct way to define the __getitem__ method in a PyTorch dataset class?
easy
A. def __getitem__(self, index, batch): return self.data[index:batch]
B. def __getitem__(self, index): return self.data[index]
C. def __getitem__(self): return self.data
D. def __getitem__(index): return self.data[index]

Solution

  1. Step 1: Check method signature requirements

    The __getitem__ method must accept self and an index parameter to return one item.
  2. Step 2: Validate return statement

    Returning self.data[index] correctly fetches the item at the given index.
  3. Final Answer:

    def __getitem__(self, index): return self.data[index] -> Option B
  4. Quick Check:

    __getitem__ needs self and index [OK]
Hint: Always include self and index parameters in __getitem__ [OK]
Common Mistakes:
  • Missing self parameter
  • Adding extra parameters not supported
  • Returning whole data instead of one item
3. Given this dataset class, what will print(len(dataset)) output?
class MyDataset:
    def __init__(self):
        self.data = [10, 20, 30, 40]
    def __len__(self):
        return len(self.data)
    def __getitem__(self, idx):
        return self.data[idx]

dataset = MyDataset()
medium
A. 4
B. 3
C. Error
D. 40

Solution

  1. Step 1: Check the data list length

    The list self.data contains 4 elements: 10, 20, 30, 40.
  2. Step 2: Understand __len__ return value

    The __len__ method returns len(self.data), which is 4.
  3. Final Answer:

    4 -> Option A
  4. Quick Check:

    len(data list) = 4 [OK]
Hint: len(dataset) calls __len__, returns data list length [OK]
Common Mistakes:
  • Confusing length with last element value
  • Expecting __getitem__ output instead
  • Forgetting to call len() properly
4. Identify the error in this PyTorch dataset class:
class Dataset:
    def __init__(self, data):
        self.data = data
    def __len__(self):
        return self.data
    def __getitem__(self, idx):
        return self.data[idx]
medium
A. __len__ should return an integer, not the data list
B. __getitem__ is missing the self parameter
C. __init__ should not accept data as argument
D. __getitem__ should return the whole data list

Solution

  1. Step 1: Check the return type of __len__

    The __len__ method returns self.data, which is a list, not an integer.
  2. Step 2: Understand expected __len__ behavior

    __len__ must return the number of items (an integer), so it should return len(self.data).
  3. Final Answer:

    __len__ should return an integer, not the data list -> Option A
  4. Quick Check:

    __len__ returns int length, not list [OK]
Hint: __len__ must return count, not the data itself [OK]
Common Mistakes:
  • Returning data list instead of its length
  • Forgetting to use len() inside __len__
  • Misdefining __getitem__ parameters
5. You want to create a PyTorch dataset that returns the square of numbers from 0 to 9. Which implementation correctly uses __getitem__ and __len__?
hard
A. class SquareDataset: def __len__(self): return 9 def __getitem__(self, idx): return idx ** 2
B. class SquareDataset: def __len__(self): return 10 def __getitem__(self, idx): return idx + idx
C. class SquareDataset: def __len__(self): return 10 def __getitem__(self): return idx * idx
D. class SquareDataset: def __len__(self): return 10 def __getitem__(self, idx): return idx * idx

Solution

  1. Step 1: Check the length method

    Since numbers 0 to 9 means 10 items, __len__ should return 10.
  2. Step 2: Verify __getitem__ returns square

    The method must accept idx and return idx * idx to give squares.
  3. Final Answer:

    class SquareDataset: def __len__(self): return 10 def __getitem__(self, idx): return idx * idx -> Option D
  4. Quick Check:

    Length 10, item = idx squared [OK]
Hint: Length matches count; __getitem__ returns square [OK]
Common Mistakes:
  • Returning wrong length (9 instead of 10)
  • Missing idx parameter in __getitem__
  • Returning sum instead of square
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard