Two syntax questions (newbie)
Duncan Booth
duncan.booth at invalid.invalid
Mon Apr 23 08:05:52 EDT 2007
Szabolcs <szhorvat at gmail.com> wrote:
> In Python this would be something like
> result = processData(list(reversed(sorted(data))))
I know that is only intended as an example, but by trying to use
Mathematica idioms in Python you are perhaps blinding yourself to using
Python's own idioms. A more Pythonic way to write your example in Python
would be:
result = processData(sorted(data, reverse=True))
sorted already returns a list, and giving it 'reverse=True' is almost
always identical to sorting and then reversing (and in the rare cases
where it matters the reverse parameter is probably what you want).
> The second question:
>
> Of course Python is not Mathematica and not as friendly with this
> style as Mma is. Sometimes it forces me to use some temporary
> variables (e.g. because lines get too long and breaking lines with a
> backslash is ugly). I like to get rid of these variables as soon as
> they aren't needed, e.g.:
>
> temp = data[:]
> temp.sort()
> temp.reverse()
> result = processData(temp)
> del temp
>
> Is it possible to avoid the explicit del temp? In C/C++ I would simply
> enclose the piece of code in curly brackets. Is it possible to somehow
> separate a block of code from the rest of the program and make
> variables local to it?
Move the code using the temporary variable into a function and it will
disappear as soon as the function returns. If you find you want to
delete the temporary before the function returns then your function is
too long.
As always there are caveats on this: don't depend on either 'del' or a
return from a function actually destroying objects immediately as any
surviving references to the value will prolong its life. Also, while the
current C-Python implementation deletes values immediately if they have
no references other Python implementations do not.
In this case the obvious fix is to use a function which copies, sorts
and reverses a sequence and then you don't need the temporary. Since
that function already exists you don't even need to write it.
More information about the Python-list
mailing list