What if you could instantly grab any piece of data without flipping through the whole pile?
Why __getitem__ and __len__ in PyTorch? - Purpose & Use Cases
Imagine you have a huge photo album with thousands of pictures. You want to show one picture at a time to your friend, but you have to flip through every page manually to find the right one.
Flipping pages one by one is slow and tiring. You might lose your place or pick the wrong photo. Doing this for thousands of pictures is frustrating and error-prone.
Using __getitem__ and __len__ lets you treat your photo album like a smart box where you can ask for any picture by its number, and it tells you how many pictures it holds. This makes accessing data fast, easy, and reliable.
for i in range(len(album)): photo = album.pages[i] show(photo)
for i in range(len(album)): photo = album[i] show(photo)
It makes your data easy to access and count, so you can train machine learning models efficiently without getting lost in the details.
When training a model to recognize handwritten digits, __getitem__ lets you quickly grab any image and its label, while __len__ tells the model how many images it can learn from.
__getitem__ lets you get data by position easily.
__len__ tells you how much data you have.
Together, they make handling datasets simple and error-free.