Why does my function not modify the list?

I am doing code challenge 2 on this page: https://www.codecademy.com/paths/computer-science/tracks/cspath-cs-101/modules/cspath-code-challenges/articles/python-code-challenges-loops

Ignoring the directions, I mistakenly tried to create a function that would modify the list instead of returning a new list.
I expected my function to modify the list passed into the function but instead its returning the list unmodified. Why is that? Based on my knowledge of python this should work but it doesn’t
Here is my code:

def add_greetings(names): for name in names: name = "Hello, " + name return names print("""Should print ["Hello, Owen", "Hello, Max", "Hello, Sophie"]""") print(add_greetings(["Owen", "Max", "Sophie"]))

You’re almost there.

I think the directions state that you have to return a new list, correct?
"In the function, create an empty list that will contain each greeting. Add the string 'Hello, ’ in front of each name in names and append the greeting to the list.

Return the new list containing the greetings."

So, how would you accomplish that? (There are hints in the directions).


Thanks for your reply.

I realize that the instructions say to create a new list, but I missed that and tried modifying the list first (oops). Ignoring the part where I’m not following directions, why is the function not modifying the list?

1 Like

Sometimes these questions will trip one up (I realized this) until I re-read the questions. :woman_facepalming:t2:

because you’re not looping through the list of names and appending to it to create a new list. You’ve supplied the argument, names and it’s just returning that.

So maybe you’d write something more like:

def add_greetings(names):
  new_greeting = []
  for name in names:
      new_greeting.append("Hello, " + name)
  return new_greeting

print(add_greetings(["Jerry", "Newman", "George", "Elaine"]))

['Hello, Jerry', 'Hello, Newman', 'Hello, George', 'Hello, Elaine']

It should be mentioned that it’s problematic to modify something you’re iterating though. I know changing the length of the iterable can be a real problem, I don’t know what effect changing the contents could have. In any case, if you wanted to change the list in place you have to refer back to the original list like this. You could also make the changes as @lisalisaj did and just make it equal to the original list, in which case you might choose not to return anything.

def add_greetings(names):

  for i in range(len(names)):

    names[i] = "Hello, " + names[i]

good_names = ["William", "Kirk", "Gunther"]