I’ll try to explain both functions with words.
return [item for sublist in l for item in sublist]
l as entry (
l is supposed to be a list)
- Return a list constructed as such : An enumeration of all the
item contained in all the
Here, each object named
sublist is required to be an iterable (e.g. a list). If called, the function will try to iterate over each
sublist item. In your case, you are feeding a list
l that contains both points and lists of points. The function will successfully iterate on all the lists of points, but will return an error when it will try to iterate on the points (which is the error you quote in your last post).
return [item for sublist in l for item in flattenList(sublist)]
Here, the function is a bit more complex. (I changed the name of the variables to match the one of the previous function)
- Given a variable
l, the function will first check if it is an instance of
collections.Iterable, which essentially dictates if Python will be able to iterate over it.
- If the object
l is an iterable (meaning that in our case, it is a list), the function will return something similar to @solamour’s function. However, Python will not iterate over
sublist but over
flattenList(sublist) : as you may notice, the function calls itself. In that case, Python will first apply
sublist, then will continue to iterate.
- If the object
l is not an iterable (e.g. it’s a Point), Python will return a list composed only of
If you are not familiar with recursive functions, try reading this : https://www.programiz.com/python-programming/recursion