Game Development Reference
In-Depth Information
The sort() List Method
26. clue.sort()
Lists have a method named sort() that rearranges the items in the list to be in
alphabetical order. Try entering the following into the interactive shell:
>>> spam = [5, 3, 4, 1, 2]
>>> spam.sort()
>>> spam
[1, 2, 3, 4, 5]
Notice that the sort() method does not return a sorted list, but rather just sorts the list
it is called on "in place". This is much like how the reverse() method works. You
would never want to use this line of code: return spam.sort() because that would
return the value None (which is what sort() returns). Instead you would want a separate
line spam.sort() and then the line return spam .
The reason we want to sort the clue list is because we might return extra clues that we
did not intend based on the order of the clues. If clue referenced the list ['Pico',
'Fermi', 'Pico'] , then that would tell us that the center digit of our guess is in the
correct position. Since the other two clues are both Pico, then we know that all we have to
do is swap the first and third digit and we have the secret number. But if the clues are
always sorted in alphabetical order, the player can't be sure which number the Fermi clue
refers to.
The join() String Method
27. return ' '.join(clue)
The join() string method returns a string of each item in the list argument joined
together. The string that the method is called on (on line 27, this is a single space, ' ' )
appears in between each item in the list. So the string that is returned on line 27 is each
string in clue combined together with a single space in between each string.
For an example, enter the following into the interactive shell:
>>> 'x'.join(['hello', 'world'])
'helloxworld'
>>> 'ABCDEF'.join(['x', 'y', 'z'])
'xABCDEFyABCDEFz'
Search WWH ::




Custom Search