# Is there a better way to flatten out a multidimensional list?

def alist(x):
if x == 1:
return 1
return [alist(x - 1), x, alist(x - 1)]
l = '%r' % alist(int(raw_input('Maximum Number Of Asterisks: ')))
f = l.replace("[", "").replace("]", "").replace(",", "").replace(" ", "")
for i in f:
print "*" * int(i)


So, basically, I just formatted the list into a string, removed all unwanted characters (left bracket, right brakcer, comma, and space), and for every number in that string, printed the appropriate amount of asterisks. If there is anything you don't understand, sorry because I had to type this up in under 2 minutes, so please just post a comment and I'll try to answer as soon as I can.

• You should clarify what exactly you want.Give us an example of the multidimensional list. – IordanouGiannis Jun 24 '13 at 20:14

Instead of replacing stuff in the repr(li), flatten the list with a recursive function..

def alist(x):
if x in (0,1): return x
return [alist(x - 1), x, alist(x - 1)]

# the magic function
def flatten(list_to_flatten):
for elem in list_to_flatten:
if isinstance(elem,(list, tuple)):
for x in flatten(elem):
yield x
else:
yield elem

l = alist(int(raw_input('Maximum Number Of Asterisks: ')))
f = flatten(l)

for i in f:
print "*" * int(i)


>>> import itertools
>>> list_of_lists = [['item_1'], ['item_2', 'item_3'], ['item_4', 'item_5', 'item_6']]
>>> chain = list(itertools.chain(*list_of_lists))
>>> print chain
['item_1', 'item_2', 'item_3', 'item_4', 'item_5', 'item_6']