122 Chapter 6
For a visual representation of the suits array and the index of
each suit, see Table 6-1.
Table 6-1: The suits Array
value "clubs" "diamonds" "hearts" "spades"
index 0 1 2 3
When we create our list suits, Python automatically assigns
an index to each value in the list. The computer starts counting at
zero, so the index of "clubs" is 0 , "diamonds" is at index 1 , and so on.
The function to find the index of an item in a list is .index(), and it
can be used on any list or array in Python.
To find the index of the suit name "clubs" in the list suits, we
call the function suits.index("clubs"). It’s like we’re asking the suits
array which index corresponds to the value "clubs". Let’s try that
in our Python shell. Enter the following lines:
>>> suits = ["clubs", "diamonds", "hearts", "spades"]
>>> suits.index("clubs")
0
>>> suits.index("spades")
3
>>>
After we create the array of suit values, suits, we ask Python
what the index of the value "clubs" is, and it responds with the
correct index, 0. In the same way, the index of "spades" is 3 , and
diamonds and hearts are at index locations 1 and 2 , respectively.
Which Card Is higher?
We created our faces array with values in order from two to ace, so
the value two, the first item in faces, would get the index 0 , all the
way through the ace at index 12 (the 13th location, starting from 0).
We can use the index to test which card value is higher—in other
words, which face value’s index is larger. Our lowest card is two,
and its index is the smallest, 0 ; the ace is our highest card, and its
index is the largest, 12.
If we generate two random face card values (my_face and
your_face), we can compare the index of my_face with the index
of your_face to see which card is higher, as follows.