def flattenList(toFlatten):
final=[]
for el in toFlatten:
if isinstance(el, list):
final.extend(flattenList(el))
else:
final.append(el)
return final
When I don't know how deeply the lists will nest, this is the only way I can think to do this.
A functional method is a method of a classic business object (BOR) or ABAP class that returns one return value only (parameter Result or Returning). However, you can also use a different method with at least one export parameter. In this case you have to specify which export parameter to use as the return value.
Several programming languages, such as TypeScript and Python, are multi-paradigm and support both OOP and functional programming to some capacity. These languages have certain allowances to utilize pure functions, and immutable objects at the developer's will.
Functional programming is based on mathematical functions. Some of the popular functional programming languages include: Lisp, Python, Erlang, Haskell, Clojure, etc. Pure Functional Languages − These types of functional languages support only the functional paradigms. For example − Haskell.
It helps us to solve problems effectively in a simpler way. It improves modularity. It allows us to implement lambda calculus in our program to solve complex problems. Some programming languages support nested functions which improve maintainability of the code.
You should avoid typechecking in Python. In this case, this means avoiding arbitrarily-nested structures where you distinguish by type. You can build your own node type which you can traverse by methods other than typechecking, like looking at a specific attribute.
For flattening one level or exactly n levels, look at itertools.chain.from_iterable
.
I don't know what you mean by "functional". This code is pretty functional: it uses recursion (not to its credit!) and it doesn't mutate its argument. (Strictly speaking, it does use mutable state for building a list, but that is just how you do it in Python.
I suppose one more functional attribute would be lazy evaluation. You could implement this thusly
def flatten(toFlatten):
for item in toFlatten:
if isinstance(item, list): # Ewww, typchecking
for subitem in flatten(item): # they are considering adding
yield subitem # "yield from" to the language
# to give this pattern syntax
else:
yield item
Recursion is very limited in Python (at least, in all its major implementations) and should generally be avoided for arbitrary depth. It is quite possible to rewrite this (and all recursive code) to use iteration, which will make this more scalable (and less functional, which is a good thing in Python, which is not especially suited for FP.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With