Thoughts on List Methods and Return Values
donod at home.com
Sat Feb 17 04:32:10 EST 2001
A recent posting (once again) discussed the fact that the list sort
method doesn't return a value. The reason being, as pointed out by
The sort() and reverse() methods modify the list in place for economy of
space when sorting or reversing a large list. They don't return the
or reversed list to remind you of this side effect.
I always considered this a fairly legitimate reason and learned to live
Till today, when I needed to take a sequence of alternate paths supplied
as a function parameter, and insert the current directory as item ,
to come up with a list of search paths. Since I wanted to allow for
tuple as well as list input, I wrote:
searchList = list(altSeq).insert(0, currPath)
And then, in order to eliminate possible empty strings, this became:
searchList = filter(None, list(altSeq).insert(0, currPath))
After a few minutes of debugging, I realized why this doesn't work.
Obviously, sort() and reverse() are not the only list methods that don't
return a value, insert() doesn't either. So, I ended up with the
searchList = list(altSeq)
searchList = filter(None, searchList)
(I won't argue the fact that this may be more readable, but that's not
Of the 9 list methods listed on page 22 of Beazley's book, here's how
they break down:
Methods that return None:
append, extend, insert, remove, reverse, sort
Methods that return a value:
count, index, pop
Which leads me to the thought that if *all* the methods which now return
None were to modify the list in place as well as return the modified
list, we would soon get used to this behaviour and achieve some coding
economy by being able to chain operations.
In other words, the above argument against sort() and reverse()
returning their result seems to be because they would then behave
differently from the other list methods, leading us to be surprised by
this behaviour. What if all the list methods returned a value? Then
there would no longer be that element of surprise.
I'm just throwing this out for discussion, knowing that it has no chance
of being implemented since it would break a lot of code.
Hmmm... after looking back at my initial incorrect (one-liner) code,
it's obvious that there's another problem -- the original input sequence
(altSeq) is modified even though it doesn't look like it is, and I might
use altSeq later on thinking it still contained it's original values.
Whereas, in the correct 3-liner, it's obvious what's being modified and
what's not. This can be easily remedied, however, by using the same
name for both input and result sequences:
altSeq = filter(None, list(altSeq).insert(0, currPath))
But, of course, there no guarantee that this will always be done.
... So, maybe it's not such a great idea after all. But after doing all
this typing I'm sure as hell not going to scrap this post ;o)
More information about the Python-list