Why doesn't variable referencing list dynamically update?

Why doesn't variable referencing list dynamically update?
0

#1

So as part of LPHW i’m making some very basic list based programs. Here I have one that lists friends in order of ‘bestness’ with position 0 being the best friend.

I allow the user to introduce a new friend and if they say that friend is a new best friend i place that friend at position one.

Since the the 0 position of the list is assigned to variable bestFriend, I expected bestFriend to reflect the new list but it holds the old value. I have to rewrite out the variable again to ‘refresh’ it as it were.

Am curious why this is. Any help much appreciated!

favFriends = ["bob", "raj", "russell"]

print("Your friends are ", favFriends)

bestFriend = favFriends[0]

print("Your best friend is ", bestFriend)

print("You've met a new friend!")

newFriend = input("What is your new friend's name? ")

newBestie = input("Are they your new best friend? y/n ")

if "y" in newBestie:
    favFriends.insert(0, newFriend)
else: pass


#why do i need this??? bestFriend = favFriends[0]

print("Your friends are ", favFriends)

print("Your best friend is ", bestFriend)


#2
bestFriend = favFriends[0]

This is not creating bestFriend as a reference to the location. It is creating a new variable that contains the value of favFriends[0] at the time that variable is created. If the value of bestFriend has changed, you need to assign the variable to the new value (you can do this in the if statement, since it’s only necessary if the user enters "y".

I’m not sure if you’ve noticed this yet, but if the new friend is not the best friend, they don’t get added to the list at all.