Algorithms — Flattening An Array/List

I remember seeing a question asked a while back about how to flatten a list that contains lists (that may contain a list as well and so on). Some answers to the question would contain an answer that would get the job done in the user’s case, but I was left wondering: how could we make a function that would solve all use cases? I began to think how the algorithm would work. What we would be doing essentially is looping through the provided list, and adding a value at index n to a sorted list if the given value was not a list itself (e.g. an integer, float, or string.) If the the item at n is a list, we recurse deeper until we run into another value that is not a list. The deeper recursive functions will compose and return lists which will be appended to the master list. Finally, we would return the variable containing the flattened master list. Here’s an example in Python:

An example of how to flatten a list in the Python language.

Now, this may not be the most efficient or fool-proof way to do it, but it works. I’m still learning, so feel free to correct any mistakes I may have made. I’ll appreciate it greatly!