This post continues where I left off in my Introduction to Python Lists. This time I'm going to
look at some examples of use of lists in the games I've written for my series of tutorials.
TicTacToe uses lists to store winning lines (which, in turn, contain lists of board locations). A
list is a good type of a collection to use in this case because when I use winlines, I iterate
over the entire list and check if a winline is completed by the player. That's what lists are
really good for: going over each item in a sequence.
RockPaperScissors uses a list to keep track of player scores: it's a list of two integers
(initially, both are 0), corresponding to players #1 and #2. That's a good example of the second
thing lists are really good at -- getting and modifying items by index.
Flashcards script uses lists to store a master copy of cards and a temporary randomized copy which
has the card removed from it after it's shown. This illustrates another useful property of lists:
they can be randomized using the built-in random.shuffle() function (I'm using the slightly
modified utils.shuffled() function in my example). Lists can also be "exhaused" using the pop()
method which returns a list item and removes it from the list at the same time (last item by
default, but you can also provide any other valid index as an argument).
In the Words game, I'm using a list to store indexes of hidden letters for each word. This list is
used in a few different ways:
- when displaying a word, each letter's index is checked against the list using 'in' operator
- when revealing a random letter, it is picked using random.choice() function
- when revealing a letter, it's index is removed using remove() method
- when generating the list, indexes are added using the append() method, which is probably the
first list method you learn when reading about lists in a Python tutorial