Skip to content
Advertisement

Regarding Python list output

Hi could someone please tell me why this code prints out the last item (“Phoebe Buffay”) on the list and not the whole list.

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []

for name in names:
  usernames = name.replace(" ","_")

print(usernames)

Thank you.

Advertisement

Answer

You’re replacing the value of usernames each time and not appending to the list as you probably want:

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []

for name in names:
  usernames.append(name.replace(" ","_"))

print(usernames)

This outputs what you expect:

['Joey_Tribbiani', 'Monica_Geller', 'Chandler_Bing', 'Phoebe_Buffay']

In your code, you’re not using the original usernames list to keep any data, instead you’re replacing what usernames is referring to for each iteration of the for loop – and after the for loop is finished, that’s the last element in your original list.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement