In a for loop - only last one is printed

Hi I have a problem in Code Challenge: Loop exercise 3:

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


   

 #Uncomment the line below when your function is done
print(add_greetings(["Owen", "Max", "Sophie"]))

Why is the append method working - so that all names are printed with Hello but not the other way --> here only the last name is printed?

Can you explain me why? :slight_smile:

Hello, @stefanbartl215503678, the way that the function is written here, each time around the for loop, the variable greet_list is reassigned. That is what the = operator does. The append() function does something different.

Add a print() statement to see what I mean.

def add_greetings(names):
  greet_lst = []
  for name in names:
    greet_lst = "Hello, " + name
    #greet_lst.append("Hello, " + name)
    print(greet_list)  # This will show how greet_list changes each time.
  return greet_lst

Now run it both ways.

3 Likes