You can write your own sorted()
like this:
try: sorted except NameError: def sorted(seq, key=None): lst = list(seq)
This will only determine your new sorted()
if there is no built-in sorted()
. First, we try to evaluate the name sorted
, and if we get a NameError
, we define our own. I use map(None, seq)
as a quick way to make a new list from seq
values.
Or, if we want to use the Schwartzian Transform for maximum efficiency, as suggested by @gnibbler:
try: sorted except NameError: import operator as op def sorted(seq, key=None): if key is not None: lst = [(key(x), x) for x in seq] lst.sort() return map(lambda x: x[1], lst) else: lst = list(seq)
source share