-1

I need transform list to "normal" list

list=[1,2,[3,4],[5,6],7,[8,9,10]]

to

list=[1,2,3,4,5,6,7,8,9,10]

Sergo
  • 15
  • 1
  • 4

2 Answers2

1

Here is my answer. Firstly, don't call your list 'list'. This prevent us from using the builtin list keyword needed for this answer.

import collections
from itertools import chain

#input list called l
l = [1,2,[3,4],[5,6],7,[8,9,10]]

#if an item in the list is not already a list (iterable) then put it in one. 
a = [i if isinstance(i, collections.Iterable) else [i,] for i in l]

#flattens out a list of iterators
b = list(chain.from_iterable(a))

print b
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Stephen Briney
  • 867
  • 5
  • 8
0

two ways:

items = [1,2,[3,4],[5,6],7,[8,9,10]]
new_list = []
[new_list.extend(x) if type(x) is list else new_list.append(x) for x in items]
print new_list

or

new_list2 = []
for item in items:
    if type(item) is list:
        new_list2.extend(item)
    else:
        new_list2.append(item)

print new_list2
Andrew Nodermann
  • 610
  • 8
  • 13