4 ms·
The definition of isIterable here is a bit fun. In most real world cases, you end up needing to specify it down a bit: isinstance(el, collections.Iterable)
by Latty 10y ago
The definition of isIterable here is a bit fun. In most real world cases, you end up needing to specify it down a bit:
isinstance(el, collections.Iterable) and not isinstance(el, str)
Is the most common one. The first clause to check if it's an iterable (as per the collections.Iterable abstract base class - for those unfamiliar, basically a check for the `__iter__()` method), the second to check it's not a string, which is also iterable, but generally you don't want to split into individual letters - and if you do, you'll need to add more checks as strings split to other 1-length strings that are still iterable, making an infinite loop.
Of course, the original problem did state "lists" explicitly, so I guess you could just type check for lists, but that's really unpythonic and not useful in the real world.