Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A class Basket has def __init__(self, items=[]) and self.items = items. Two baskets are made with no argument, and "apple" is added to the first. What does the second basket hold, and why? Write the corrected __init__.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. The default value [] is made once, when Python reads the def, and every object that uses the default shares that one list.
So the second basket also holds ["apple"]: both baskets point to the same list.
The fix. Use None as the default, and make a new list inside.
Check. The output is ['apple'] []. Each basket has its own list.
Answer: The second basket holds ["apple"] too, because the default list is shared. Use items=None and make the list inside.
Log in to join the discussion.
Loading…