steve at holdenweb.com
Sat Jan 30 16:45:45 CET 2010
Dan Brown wrote:
> Why does extending a list with the empty list result in None? It
> seems very counterintuitive to me, at least --- I expected ['a'].extend
> () to result in ['a'], not None.
How very inconvenient of Python! What it actually does is create an
anonymous list containing only the element 'a', and leave it unchanged
by extending it with an empty list. Since there is no longer any
reference to the list it has become garbage.
Contrast that with:
>>> lst = ['a']
['a', , '1']
As you can see by the absence of output, both the .extend() and
.append() list methods return None. They mutate the list instance upon
which they are called.
In your example you were expecting the methods to return the mutated
list. They don't.
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/
More information about the Python-list