B. front_x Given a list of strings, return a list with the strings in sorted order, except group all the strings that begin with \'x\' first. e.g. [\'mix\', \'xyz\', \'apple\',
You could sort words with one call to sorted using the key parameter to "teach" sorted how you wish the items in words to be ordered:
def front_x(words):
return sorted(words, key=lambda word: (word[0] != 'x', word))
The key function is called once for every item in words and returns a proxy value by which the items in words is to be sorted. tuples such as the one returned by the lambda function above, are sorted in lexicographic order (according to the first item in the tuple, and according to the second to break ties).
This technique as well as others is explained in the excellent Sorting Howto.
For example,
print(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']))
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
Note that if words contains an empty string, word[0] will raise an IndexError. In contrast ''.startswith('x') returns False.
So use word.startswith('x') if you wish front_x to handle empty strings, and use word[0] == 'x' if you wish to raise an exception.