Suppose I have a list containing (among other things) sublists of different types:
[1, 2, [3, 4], {5, 6}]
that I’d like to flatten in a selective way, depending on the type of its elements (i.e. I’d like to only flatten sets, and leave the rest unflattened):
[1, 2, [3, 4], 5, 6]
My current solution is a function, but just for my intellectual curiosity, I wonder if it’s possible to do it with a single list comprehension?
List comprehensions aren’t designed for flattening (since they don’t have a way to combine the values corresponding to multiple input items).
While you can get around this with nested list comprehensions, this requires each element in your top level list to be iterable.
Honestly, just use a function for this. It’s the cleanest way.