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.
Example
Below is a demonstration for the same −
my_list = [[[11,[[32]],[[[53]]]],[[64],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))
Output
The original list is : [[[11, [[32]], [[[53]]]], [[64], 75]], [[6, 89, 99]]] The flattened list is : [11, 32, 53, 64, 75, 6, 89, 99]
Explanation
- A nested list is defined, and is displayed on the console.
- The elements are summed up using the ‘sum’ method, and this is applied to every element using the ‘map’ method.
- This operation’s result is assigned to a variable.
- It is displayed as output on the console.