0

I have a two python list like this

l1 = [[1,2],[3,4],[6,7]]
l2 = [[1,2],[3,4],[6,7],8]

I was able to flatten the list l1 like below

flattend_list = [e for sub in l1 for e in sub]

But I' unable to do it for list 2. I am not able to figure out how to add if else condition before 2nd for loop inside a primary for loop in list comprehension. Any idea, Thanks in advance.

Vikas Garud
  • 143
  • 2
  • 10
  • I don't think this should have been closed as the author is asking specifically how to flatten withing a list comprehension, which is different from the linked question. – James Jun 05 '23 at 13:04
  • @James I think link question addresses the issue. They have an example `[[[1, 2, 3], [4, 5]], 6]` – Talha Tayyab Jun 05 '23 at 13:08
  • And plenty of the answers use list comprehensions: `[x for sub in l2 for x in (sub if isinstance(sub, list) else [sub])]` which works for 2 levels. – user2390182 Jun 05 '23 at 13:15

0 Answers0