Reputation: 137
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...
Upvotes: 0
Views: 189
Reputation: 107307
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]]]
Upvotes: 3