0

Is there a built-in function in Python 3 for the function lambda x: x? Sometimes it may make some code more elegant. For example:

def my_sort(lst, key):
    ...

lst = [4, 3, 7, 1, 9]
my_sort(lst, key=lambda x: x)   # probably it can be written in a better way WITHOUT lambda x: x with the help of a standard function

I need a build-in or standard function in Python 3, not an expression like lambda x: x of a different way to improve my code.

Fomalhaut
  • 8,590
  • 8
  • 51
  • 95
  • 6
    `key=None`?.... Why even have a key? – cs95 Nov 08 '17 at 11:30
  • @COLDSPEED `None` is not a function. – Fomalhaut Nov 08 '17 at 11:42
  • You asked for something that is more elegant... what else do you want? `lambda x: x` happens to be the identity function which `None` expertly mimics. – cs95 Nov 08 '17 at 11:44
  • You still haven't explained your reason/purpose for doing this, I don't see the reason for an identity function. – cs95 Nov 08 '17 at 11:45
  • Remember, you could just do `def my_sort(lst, key=None):` and neglect to pass `key` so the default is implied, indeed that's how `sorted` is defined. – cs95 Nov 08 '17 at 11:45
  • 1
    Perhaps you should show us a better example that illustrates where an identity function would actually be useful. FWIW, there's nothing wrong with `lambda x: x` if it does the job (although it isn't as fast as a function coded in C would be), and the function you're passing it to doesn't accept a special value like `None` to indicate that it should use the identity function. – PM 2Ring Nov 08 '17 at 11:46
  • 2
    I guess you could do `identity=functools.partial(lambda x: x)`. :) – PM 2Ring Nov 08 '17 at 11:49
  • My question is correct. I'm asking for a Python standard function, like `operator.getitem(0)`, or a build-in function to make my code more elegant than `lambda x: x`. – Fomalhaut Nov 08 '17 at 11:51
  • That would imply performing some kind of _operation_ on the input, which you're not doing. You basically want to find another way to do `def f(x): return x`. There really isn't. – cs95 Nov 08 '17 at 11:53
  • @cᴏʟᴅsᴘᴇᴇᴅ, @pm-2ring commented way using `partial` seems well enough for doing an identity function – Netwave Nov 08 '17 at 12:05
  • @DanielSanchez It's still a wrapper around the lambda... and at that point you might as well define `def f(x): return x` and pass `f` to `my_sort`, right? – cs95 Nov 08 '17 at 12:10
  • @cᴏʟᴅsᴘᴇᴇᴅ, yep, actually `def identity(x) : return x` seems pretty legit. you are 100% right :) – Netwave Nov 08 '17 at 12:19

1 Answers1

1

A pythonic approach would be to use a default argument of None that makes key optional:

def my_sort(lst, key=None):
    if key is None:
        key = lambda x: x
    ...

lst = [4, 3, 7, 1, 9]
my_sort(lst)
Mike Müller
  • 82,630
  • 20
  • 166
  • 161