How can I modify this list so that all p\'s appear at the beginning, the q\'s at the end, and the values in between are sorted alphabetically?
You can use the following lambda function as the key in sorted():
l1 = sorted(l, key=lambda x: ((x == 'q') - (x == 'p'), x))
print(l1)
# ['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']
The function generates the following comparison keys:
func = lambda x: ((x == 'q') - (x == 'p'), x)
for i in l1:
print(func(i))
Output:
(-1, 'p')
(-1, 'p')
(0, 'a')
(0, 'b')
...
(0, 't')
(0, 'z')
(1, 'q')
(1, 'q')