Question: In this problem, you will use recursion to write a function named flatten ( ) that accepts a single parameter x , which is expected

In this problem, you will use recursion to write a function named flatten() that accepts a single parameter x, which is
expected to be a list. Some of the elements of x might themselves be lists, and some of the elements of those lists could
again be lists, and so on. We will assume that the lists could be nested within each other to an arbitrary depth. The function
should "flatten" the structure of the nested lists by creating a single list that contains all of the non-list values stored within
the structure, but no other lists.
For example, let nested_list =[1,[8,[5,6,[4,9]]],[7,2,3]]. Then flatten(nested_list)
should return the list [1,8,5,6,4,9,7,2,3].
5
Write a function flatten() that accepts accepts a parameter x intended to represent a list that perhaps contains other
lists. The function should return a flattened version of x by performing the following steps:
1. Create an empty list named flat_list.
2. Loop over the elements of x. For each iteration of the loop, perform the following steps:
a. If the current element of x is a list, then called flatten() on that element, concatenating the result
to flat_list.
b. If the current element of x is not a list, then append it to flat_list.
3. Return flat_list.
We will now test the function.
In a new code cell, call flatten() on each of the following lists. Print the result of each function call.
[1,2,3]
[1,[2],[3]]
[1,[2],[[4,5],6]]
[1,[8,[5,6,[4,9]]],[7,2,3]]

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!