0

I have an array of lists and I want to convert it into single dimensional array. I can do it with 2 "for" loops but one prohibition is that I have to do it as it was N-dimensional array.

original_list = [[2,4,3,[1,2]],[1,5,6], [9], [7,9,0]]
martineau
  • 119,623
  • 25
  • 170
  • 301
  • This is actually a different question @prune. Try applying any of those methods and you will get alist of lists and inegers – yatu Dec 17 '18 at 20:57
  • 1
    The actial duplicate is https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists – yatu Dec 17 '18 at 21:00
  • 1
    @nixon I the dup I used, at least two of the answers deal with arbitrary nesting levels. However, the one you gave is easier to find; I've added it to the duplicates list. Thanks. – Prune Dec 17 '18 at 21:42

1 Answers1

0

Just use chain from itertools:

Code:

import itertools as it

original_list = [[2,4,3,[1,2]],[1,5,6], [9], [7,9,0]]

print(original_list)

new_list = list(it.chain.from_iterable(original_list))

print(new_list)

Output:

[[2, 4, 3, [1, 2]], [1, 5, 6], [9], [7, 9, 0]]
[2, 4, 3, [1, 2], 1, 5, 6, 9, 7, 9, 0]
trsvchn
  • 8,033
  • 3
  • 23
  • 30