khpeek khpeek - 5 months ago 11
Ruby Question

Chain together methods in Python as in Ruby

In Ruby, one can chain together methods like so:

a = [2,3,1]
b = a.sort.reverse


which sets the value of the variable
b
to
[3,2,1]
while leaving
a
the same.

I'd like to perform similar operations in Python. So far, the shortest way to do this I have found is:

import copy
a = [2,3,1]
b = copy.copy(a)
b.sort()
b.reverse()


That is, with 5 lines of code instead of 2. Is there really no simpler way?

Answer

You can write this down pretty much directly.

a = [2,3,1]
b = sorted(a, reverse=True)

Even if you want to use only methods, you can do that rather straightforward as well:

a = [2,3,1]
b = a.copy()  # a[:] in python2
b.sort(reverse=True)

Python tends to be rather picky about implicit cloning. Copying references is cheap, copying objects is expensive. Since many python types are mutable, one can easily introduce subtle bugs when things are cloned (or not) by accident. Thus, most interfaces need you to explicitly clone things.