Python Introducing Lists Using Lists Mutability

David Dong
David Dong
5,593 Points

Why wasn't wishes[0] used instead of wishes.pop(0)?

.pop(0) removes an item from the list, but wishes[0] doesn't. He ended up copying the list, but why not just use wishes[0] instead?

1 Answer

Chris Freeman
Chris Freeman
Treehouse Moderator 59,490 Points

Good question! Since the parameter wishes is mutable (changeable) list, by using .pop() it modifies the contents of the list seen outside of the function call. This “side effect” might not be desirable. My making a copy, this prevents changing the list seen outside of the function.

As for why pop(0) vs [0], the desire is to suggest the first item in the list then display the remainder of the list. This could also have been accomplished without using the copy:

suggested_gift = wishes[0]
for wish in wishes[1:]:

by using the wishes[1:] slice, a copy is automatically created.

Post back if you need more help. Good luck!!!