Why doesn't python's list append() method return the list itself?
Thomas Jollans
thomas at jollans.com
Sun Jul 11 12:19:35 EDT 2010
On 07/11/2010 05:59 PM, dhruvbird wrote:
> Why doesn't python's list append() method return the list itself? For
> that matter, even the reverse() and sort() methods?
> I found this link (http://code.google.com/edu/languages/google-python-
> class/lists.html) which suggests that this is done to make sure that
> the programmer understands that the list is being modified in place,
Yes!
> but that rules out constructs like:
> ([1,2,3,4].reverse()+[[]]).reverse()
No!
you can either approach this by imperatively modifying a list in-place:
L = [1,2,3,4]
L.reverse()
L.append([])
L.reverse()
Or you can use a more functional style:
L2 = reversed(reversed([1,2,3,4]) + [[]])
(or ([1,2,3,4][::-1]+[[]])[::-1], if you like that kind of thing)
Imagine list.reverse and list.append *did* return self:
L1 = [1,2,3,4]
L2 = L1.reverse().append([]).reverse()
would you expect, after this code, that (L1 == L2) and (L1 is L2)? I
think it would surprise a lot of people. Better clearly separate
modifying an object and functionally processing an object.
Cheers
Thomas
More information about the Python-list
mailing list