If you want to modify finished_list
, you should pass it to your function as a parameter, and then call methods on it that will modify that original list, rather than assigning a different list to the same name:
def add_items(existing_items):
add_list = input(
"Please enter your additional items separated by space: "
).split()
existing_items.extend(add_list)
existing_items.sort()
and then call this with:
add_items(finished_list)
in order to add the items to finished_list
.
The important distinction is in the way that the assignment operator works (I used existing_items
as the parameter name above in order to make the following example easier to follow):
>>> finished_list = [1, 2, 3]
>>> existing_items = finished_list
>>> existing_items.extend([4, 5, 6])
>>> finished_list
[1, 2, 3, 4, 5, 6]
In the above example, I extend
existing_items
with more items, and because the name existing_items
refers to finished_list
, the new items show up in that list. What happens if instead I assign to existing_items
?
>>> finished_list = [1, 2, 3]
>>> existing_items = finished_list
>>> existing_items = existing_items + [4, 5, 6]
>>> finished_list
[1, 2, 3]
>>> existing_items
[1, 2, 3, 4, 5, 6]
Because I did an assignment, I now have two different lists, and the original finished_list
isn't affected. (Note that if I do things like existing_list.extend(...)
at this point, it still won't affect finished_list
, because existing_list
ceased to reference finished_list
as soon as I did existing_list = ...
.) You get the same exact behavior when you do this type of assignment inside a function, even if both of the variables are named finished_list
, because the body of a function has its own namespace and can have its own variables that "shadow" variables of the same name in the calling namespace.
One more example, using slice assignment, which is what you were attempting to do in your function at one point:
>>> finished_list = [1, 2, 3]
>>> existing_items = finished_list
>>> existing_items[:] = existing_items + [4, 5, 6]
>>> finished_list
[1, 2, 3, 4, 5, 6]
Slice assignment is an operation that modifies the elements of a existing list rather than assigning a new name to another list. It looks very similar to a regular assignment, and in many cases might appear to behave identically, but it's very different, as the above examples show.