The following is a little modified version of your code but reads much cleaner and easier to understand:
def flatten(val):
print('--------', val, '----------')
o = []
for thing in val:
print(thing, type(thing))
if isinstance(thing, int):
o.append(thing)
if isinstance(thing, list):
for a_thing in thing:
if isinstance(a_thing, int):
o.append(a_thing)
return o
if __name__ == '__main__':
result = flatten([0, [1], 2])
print result
[0, 1, 2]
Some suggestion:
While this script may be OK for experimenting however you may eventually need recursion to solve such problems. Recursive functions are a kind of function that call itself to get a job done. A question to ask is: what if your input array contains [0, [1,2,3], [4]]? In such case your will need a nested loop to solve the problem. The problem becomes more complicated when your input looks like: [0, [1,2,[3, 4]], [5]]. In such cases recursive functions are used.
Here is how a recursive function could solve the problem:
def flatten(*args):
number_list = []
for item in args:
if isinstance(item, int):
number_list.append(item)
else:
number_list += flatten(*item)
return number_list
if __name__ == '__main__':
print flatten([0, [1, 2, [3, 4, 5]], 6])
[0, 1, 2, 3, 4, 5, 6]