When it is required to flatten a list without using recursion technique, the lambda function, ‘sum’ method, ‘map’ method and the ‘isinstance’ method can be used.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
The ‘isinstance’ method checks to see if a given parameter belong to a specific data type or not.
Anonymous function is a function which is defined without a name. In general, functions in Python are defined using ‘def’ keyword, but anonymous function is defined with the help of ‘lambda’ keyword. It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it.
The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.
The ‘sum’ method adds numeric values present in an iterable.
Below is a demonstration for the same −
my_list = [[[11,[],[[]]],[,75]], [[6, 89, 99]]] flattened_list = lambda my_list: sum(map(flattened_list,my_list),) if isinstance(my_list,list) else [my_list] print("The original list is : ") print(my_list) print("The flattened list is :") print(flattened_list(my_list))
The original list is : [[[11, [], [[]]], [, 75]], [[6, 89, 99]]] The flattened list is : [11, 32, 53, 64, 75, 6, 89, 99]