Stackoverflow question: Is there a built-in identity function in Python?

Nathan Ernst nathan.ernst at gmail.com
Thu Dec 7 15:12:03 EST 2017


There is a built-in identity function in Python. The function is called
'id'. See https://docs.python.org/3/library/functions.html#id Note that
this will not behave the same across different Python runtimes. e.g.
CPython, IronPython or Jython all implement this differently.

An example:

Python 3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 1
>>> b = 2
>>> id(a)
10911168
>>> id(b)
10911200
>>> c = 1
>>> id (c)
10911168

Regards,
Nathan

On Thu, Dec 7, 2017 at 1:46 PM, Paul Moore <p.f.moore at gmail.com> wrote:

> On 7 December 2017 at 18:28, Ethan Furman <ethan at stoneleaf.us> wrote:
> > The simple answer is No, and all the answers agree on that point.
> >
> > It does beg the question of what an identity function is, though.
> >
> > My contention is that an identity function is a do-nothing function that
> > simply returns what it was given:
> >
> > --> identity(1)
> > 1
> >
> > --> identity('spam')
> > 'spam'
> >
> > --> identity('spam', 'eggs', 7)
> > ('spam', 'eggs', 7)
> >
> > Of the five answers to that SO question, mine is the only one that will
> > correctly handle those three examples.  If you agree with my contention
> feel
> > free to up-vote my answer.  :)
>
> IMO (as a mathematician ;-)) the identity function is a
> *single-argument* function that returns the value passed to it. So:
>
>     def identity(x):
>         return x
>
> See https://en.wikipedia.org/wiki/Identity_function
>
> identity(1,2) is an error.
>
> Extending the definition to multiple arguments causes all sorts of
> confusion, as you've seen.
>
> Paul
> --
> https://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list