-2

I am making a blackjack console game. Basically one function that I have created and need for this program is a function that outputs the hands, for both the player and the dealer. If you have ever played blackjack you will know that the dealer has one card hidden. So the when this function outputs the hands, it is supposed to replace the first value in the dealer's hand list with a question mark. And it does this. But it also modifies the list outside of the function, which is a problem. I have isolated the function into a script by itself to make sure that it is the root cause of the issue, and not something else in my program:

def outputDecks(a, b, hiddenBool):
    bModif = b

    if hiddenBool == True:  
        bModif[0] = "?"

    print("Player Cards: " + str(a))
    print("Dealer Cards: " + str(bModif) + "\n")


a = [1, 2, 3, 4]
b = [5, 6, 7, 8]

outputDecks(a, b, True)

print(a)
print(b) 

And here is the output:

Player Cards: [1, 2, 3, 4]
Dealer Cards: ['?', 6, 7, 8]

[1, 2, 3, 4]
['?', 6, 7, 8]

I hope you can see the problem here. I have inputted the lists into the function. List b, the one that needs to be displayed with the question mark, has its contents copied into a new variable, and that variable is modified with the question mark. Yet when I print the list after running the function, the question mark is not there. But I never modified the original list, so why is there a question mark? I hope this is not a really dumb issue with an obvious fix and I am wasting y'all's time, but I have been staring at this issue for nearly an hour and can't figure it out. I tried googling and couldn't find a solution, likely due to me not knowing how to word the search. I really hope y'all can help me.

Zoe stands with Ukraine
  • 25,310
  • 18
  • 114
  • 149

2 Answers2

2

you need to copy b or bModif will be by-reference

    bModif = b.copy()
ti7
  • 12,648
  • 6
  • 30
  • 60
2

List b, the one that needs to be displayed with the question mark, has its contents copied into a new variable, and that variable is modified with the question mark

This is where the problem occurs. bModif = b doesn't copy b content into bModif. bModif is a reference to the same list that b refers to. If you want a copy of a list in python, use bModif = b.copy()

Lim H.
  • 9,514
  • 9
  • 46
  • 74
  • Thanks. Honestly don't know how I have never heard of this before. Is this something only in the newer versions of python. Because I have been using python since 2.7 and genuinely never encountered this before – Jeffery Johnson Jan 11 '22 at 17:06
  • Nope, it has been this way since forever. I think you probably have never passed objects like list and re-assign them before today. Passing and reassigning primitives, e.g. integers, won't cause this issue, which you might run into more often in practice. – Lim H. Jan 11 '22 at 17:08