No swap function in Python?

Nick Perkins nperkins7 at home.com
Thu May 31 18:43:00 EDT 2001


hehehehehe,..smart-ass!
(well done)

(..but technically a bit of cheat, passing the names...)


"Ben Wolfson" <wolfson at uchicago.edu> wrote in message
news:20010531.171417.492067917.1966 at bur-jud-175-024.rh.uchicago.edu...
> In article <slrn9hd2cs.iiu.scarblac at pino.selwerd.nl>, "Remco Gerlich"
> <scarblac at pino.selwerd.nl> wrote:
> >
> > A swap function is impossible in Python. A function cannot rebind names
> > in the caller's namespace. This is why del is a statement and not a
> > function, for instance.
>
> >>> a = 10
> >>> b = 5
> >>> def swap(**d):
>         assert len(d) == 2, 'Only swaps two variables!'
>         import sys
>         loc = sys._getframe(1).f_locals
>         k1, k2 = d.keys()
>         loc[k1] = d[k2]
>         loc[k2] = d[k1]
>
> >>> swap(a=a, b=b)
> >>> print a, b
> 5 10






More information about the Python-list mailing list