Trying to understand why my p1 instances changes when update the p2 instance

Very new to python. So here is my question.
I was just wondering why the “dice” end up being the same after I call p2.update_dice(). I would guess it is something stupid on my part, maybe related to the outside functions. Thanks

output:
Welcome to Duh Dice!
Would you like instructions Y/N? n
let’s play.
before it is set
[1, 2, 4, 5, 6]
player: Jim dice = [1, 2, 4, 5, 6]
before it is set
[2, 3, 3, 4, 5]
player: Jim dice = [2, 3, 3, 4, 5]
player: Ted dice = [2, 3, 3, 4, 5]



class Player:
    def __init__(self, p_name, p_score, p_dice):
        self.p_name = p_name  # player name
        self.p_score = p_score  # player points
        self.p_dice = p_dice 
        
    def update_dice(self):
        print('before it is set {}'.format(self.p_dice))
        self.p_dice = get_dice()        


p1 = Player('Jim', 12, [])
p2 = Player('Ted', 11, [])


# some vars
# num of die to roll , initial five
num_of_dice = 5
dice_rolled = []
roll = 0


def get_die():
    die = random.randint(1, 6)
    return die


def get_dice():
    dice_rolled.clear()
    for i in range(num_of_dice):
        dice_rolled.append(get_die())
    dice_rolled.sort()
    print(dice_rolled)
    return dice_rolled


def display_instructions():
    print('Welcome to Duh Dice!')
    ans = input('Would you like instructions Y/N? ')
    if ans.upper() == 'Y':
        print('How to play.....')
    elif ans.upper() == 'N':
        print("let's play.")
    else:
        print('please enter Y/N')
        display_instructions()


display_instructions()

p1.update_dice()
print('player: {} dice = {}'.format(p1.p_name, p1.p_dice))
p2.update_dice()
print('player: {} dice = {}'.format(p1.p_name, p1.p_dice))
print('player: {} dice = {}'.format(p2.p_name, p2.p_dice))

This line:

self.p_dice = get_dice()

binds p_dice to the result of get_dice(), which returns a reference to (i.e. points to) the list that the global variable dice_rolled refers to.

After calling p1.update_dice(), p1.p_dice refers to the list that dice_rolled refers to, and after calling p2.update_dice(), p2.p_dice also refers to that list.

Understood, so would wrapping get_dice() in list make sense?
Thanks!

self.p_dice = list(get_dice)) 

If you want get_dice to return an independent list every time it is called, you should make the change in that function instead.

However, there’s no reason for dice_rolled to be global variable at all; get_dice clears it and repopulates it every time, it should just create a new list and return it.

Thanks, that makes sense, code is changed and works as expected.