0

here i need to merge list of lists with a boolean item.

Input like this

list = [[[3, [1, 2]]], [[1, [2, 3]]], False, [[4, [4, 5]]]]

And excepted result is

[[3, [1, 2]], [1, [2, 3]], False, [4, [4, 5]]]

I tried this

res = []
for x in list:
   res.append(x)
print res

Thanks in advance...

Jothimani
  • 137
  • 1
  • 10
  • take a look a this [flatten (an irregular) list of lists in python](http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python) any of the answers can be modify to only one level of nesting – Copperfield Feb 02 '16 at 18:07

1 Answers1

3

You can use a list comprehension to preserve the first element of your sub lists if they are valid (if sub) otherwise the sub list itself:

>>> lst = [[[3, [1, 2]]], [[1, [2, 3]]], False, [[4, [4, 5]]]]
>>> [sub[0] if sub else sub for sub in lst]
[[3, [1, 2]], [1, [2, 3]], False, [4, [4, 5]]]

Note : Don't use python keywords and built-in type's names as your variables and object names.

As @Padraic Cunningham suggested, for a more precise way you can use isinstance():

>>> [sub[0] if isinstance(sub, list) else sub for sub in lst]
[[3, [1, 2]], [1, [2, 3]], False, [4, [4, 5]]]
Omid
  • 2,617
  • 4
  • 28
  • 43
Mazdak
  • 105,000
  • 18
  • 159
  • 188