Skip to content Skip to sidebar Skip to footer

Python Iterator - For I In [something]

In the Following code: class Box: def __init__(self): self.volume = [] self.index = -1 def add_item(self, item): self.volume.append(item) def

Solution 1:

Question 1) - What does for items in b mean? what is it referring to? what is in b?

This is documented:

Question 2) - Assuming it refers to the the three items we added to it. Why does it go on infine loop stuck on: The potato weighs 2 kg and Not going to the other 2 elements? (It works fine if I increment )

Because if you don't increment the index, it's never greater than len(self.volume), so your iterator always yields the same object and never raises StopIteration.

EDIT

shouldn't it be 'for i in b.volume' as we added items in volume variable not in 'b'?

Well, the point of making Box an iterable (and an iterator) is actually to hide how Items are stored (law of demeter)- note how the client code uses Box.add_item(), not Box.volume.append().

The current implementation is faulty though as it exposes .volume and index as part of the public API when they should be protected (names prefixed with a single leading underscore, which is the Python convention for "protected" attributes), and it's possibly a bit incomplete too (it should at least expose a way to know if the box is empty / how many items it contains).

Post a Comment for "Python Iterator - For I In [something]"