I am trying to write code that produces a deck of cards. The deck is a 2D array that contains each card as an array. Each card array contains its card value as well as its suit, represented by the values 0 to 3. However, the code outputs this:
[[ 1. 1.]
...
[13. 1.]
[ 1. 1.]
...
[13. 1.]
[ 1. 2.]
...
[13. 2.]
[ 1. 3.]
...
[13. 3.]]
The first 13 indecies are my issue here, as the code I have written I believe should output [1. 0.]
up until [13. 0.]
My code is designed to have 13 of each suit, increasing from 1 to 13 (inclusive). Index 0 of each card represents the card value, Ace to King. Index 1 represents its suit (0=S,1=H,2=C,3=D).
suits = 4
suitsize = np.empty(shape=(13,2))
suitsize[:,0] = np.arange(1,suitsize.shape[0]+1)
a = suitsize
print(suitsize)
for i in range(1,suits):
a[:,1] = i
suitsize = np.concatenate([suitsize,a])
print(suitsize)
Whether I use np.empty, or np.zeros, the first 13 indecies all still have their index 1 value (suit) replaced with 1. This means that I end up producing a deck of cards with 0 spades, 26 hearts, 13 clubs, and 13 diamonds.
If anyone could explain to me what is happening here or a fix, please let me know. Thank you!
You have a classic NumPy issue — mutable arrays. The problem is that when you write a = suitsize
, you're not creating a new copy of the array. You're just making a new reference to the same array in the computer's memory. So when you do a[:,1] = i
, you're also modifying suitsize
at the same time.
You need to create an actual copy of the array, not just a reference. Just change this line a = suitsize
to a = suitsize.copy()
.