Flattening lists
Sion Arrowsmith
siona at chiark.greenend.org.uk
Thu Feb 5 11:49:22 EST 2009
mk <mrkafk at gmail.com> wrote:
>Brian Allen Vanderburg II wrote:
>> I think it may be just a 'little' more efficient to do this:
>>
>> def flatten(x, res=None):
>> if res is None:
>> res = []
>> for el in x:
>> if isinstance(el, (tuple, list)):
>> flatten(el, res)
>> else:
>> res.append(el)
>> return res
>
>
>Hmm why should it be more efficient [than
def flatten(x):
res = []
for el in x:
if isinstance(el,list):
res.extend(flatten(el))
else:
res.append(el)
return res
]? extend operation should not be very costly?
It's not a question of extend/append, it's the fact that your
original function creates (and destroys) a new list for every
recursive call. Which, if you've got large nested lists, will
have an impact.
--
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
"Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
More information about the Python-list
mailing list