Tail recursion to while iteration in 2 easy steps
Chris Angelico
rosuav at gmail.com
Thu Oct 3 00:14:27 EDT 2013
On Thu, Oct 3, 2013 at 12:34 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> py> def f():
> ... a = (1, 2, 3)
> ... b = (1, 2, 3)
> ... return a is b
> ...
> py> f() # Are the tuples the same object?
> False
That just means the compiler doesn't detect reuse of the same tuple.
But compare:
>>> def f():
return (1,2,3)
>>> f() is f()
True
Every time the function's called, it returns the same tuple (which
obviously can't be done with lists). And of course if that would be
dangerous, it's not done:
>>> def f():
return (1,[2],3)
>>> f()[1].append("Hello")
>>> f()
(1, [2], 3)
>>> import dis
>>> dis.dis(f)
2 0 LOAD_CONST 1 (1)
3 LOAD_CONST 2 (2)
6 BUILD_LIST 1
9 LOAD_CONST 3 (3)
12 BUILD_TUPLE 3
15 RETURN_VALUE
ChrisA
More information about the Python-list
mailing list