The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

Marko Rauhamaa marko at pacujo.net
Tue Mar 15 06:14:07 EDT 2016


BartC <bc at freeuk.com>:

> But how do you pass something that refers to a itself?
>
> There are good reasons for wanting to do so. Try writing this function
> in Python:
>
> def swap(a,b):
>     b,a = a,b

Have you tried writing same function in Java? Java is a hugely
successful, highly performant programming language that suffers from the
same "flaw." It doesn't allow you to call functions by reference.

Python has it easier because multiple values can be returned in a tuple,
but ad hoc tuples don't exist in Java. Thus, arrays are commonly used to
implement a sort of pass-by-reference. Here's how to demonstrate the
idea in Python:

   def swap(aref, bref):
       aref[0], bref[0] = bref[0], aref[0]

   x = "one"
   y = "two"
   xref = [x]
   yref = [y]
   swap(xref, yref)
   x = xref[0]
   y = yref[0]
   print(x, y)


Marko



More information about the Python-list mailing list