Skip to content
Advertisement

How to include condition in composite list comprehension?

I would like to flatten a list but keep NaNs. The following base code works when there are no NaNs:

JavaScript

Now if I have the following case it will break:

JavaScript

which makes sense, but I need this border case to be handled and I’m not sure how to add the special case condition in the list comprehension above. How can I modify such comprehension to cover such case?

The expected output is:

JavaScript

Advertisement

Answer

I would check to see if the sublist is iterable. If not then wrap it in a tuple to then be flattened:

JavaScript

Using chain from itertools would make it a bit cleaner:

JavaScript

Source for checking if iterable (StackOverflow)

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement