I am out of trial and error again Lists
steve+comp.lang.python at pearwood.info
Sat Oct 25 09:44:42 CEST 2014
Rustom Mody wrote:
> On Saturday, October 25, 2014 11:20:03 AM UTC+5:30, Chris Angelico wrote:
>> On Sat, Oct 25, 2014 at 4:40 PM, Rustom Mody wrote:
>> > Its generally accepted that side-effecting functions are not a good
>> > idea -- typically a function that returns something and changes global
>> > state.
>> Only in certain circles. Not in Python. There are large numbers of
>> functions with side effects (mutator methods like list.append,
>> anything that needs lots of state like random.random, everything with
>> external effect like I/O, heaps of stuff), and it is most definitely
>> not frowned upon.
>> In Python 3 (or Python 2 with the future directive), print is a
>> function, print() an expression. It's not "semantically a statement".
> So give me a valid (ie useful) use where instead of the usual
> we have
Your question seems to be non-sequitor. To me, it doesn't appear to have any
relationship to Chris' comments.
But to answer your question, Ruby has mutator methods like list.append
return the list being mutated, to make it easy to chain multiple calls:
That would make it easy and convenient to modify a list immediately pass the
modified list to a function and embed it in an expression:
# Python's way
values = [1, 2, foo(l), 3]
# Pseudo-Ruby way
values = [1, 2, foo(l.append(4)), 3]
Languages where all values are immutable *by definition* have to return a
new list, since you can't modify the original, hence they too can easily be
embedded in an expression.
Many people try to write something like this:
old_lists = [a, b, c, d]
new_lists = [thelist.append(x) for thelist in old_lists if len(thelist) < 5]
only to be unpleasantly surprised to discover than new_lists now contains
None instead of the lists. Having methods return a result rather than
behave like a procedure is a valid (i.e. useful) design choice.
More information about the Python-list