# 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

## 3 Answers

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)


Without many details, maybe the following can help you:

>>> 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']


Take a look at this question, there are some answers that might help you.

• Thanks for the effort, evil_inside, but that would only flatten out a 2-dimensional list, not anything higher. In my solution, I could easily use the split() method and not remove the spaces in the string to separate the string by the spaces (that sounds confusing) and make a 1-dimensional list from any multidimensional list. – SCE Jun 24 '13 at 22:04

Go to this link from the python tutorials. Read this completely or just search for flat. That is an easy way to flatten lists.

Now you may say that it is not good for multidimensional lists. Then I would say that you can use recursion to solve the problem. Think about that.