3 ms·
Gee, that's almost exactly what I got: def flatten(nested_list): output_list = [] for elem in nested_list: if type(elem) == list:
by canadian_voter 10y ago
Gee, that's almost exactly what I got:
def flatten(nested_list):
output_list = []
for elem in nested_list:
if type(elem) == list:
output_list.extend(flatten(elem))
else:
output_list.append(elem)
return output_list
I think that's easier to read than the following, and appears to run slightly faster as well?
import collections
def flatten(nested_list):
if isinstance(nested_list, collections.Iterable):
return [a for i in nested_list for a in flatten(i)]
else:
return [nested_list]