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?
p\'s
q\'s
Use the key parameter in sorted:
key
l = ['f','g','p','a','p','c','b','q','z','n','d','t','q'] def key(c): if c == 'q': return (2, c) elif c == 'p': return (0, c) return (1, c) result = sorted(l, key=key) print(result)
Output
['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']