Language: Python
Topic: Lists
Function name :
flatten_list
Parameters : aList (list)
Returns: final_list (list)
Description : Write a function that takes in a
list and returns a new list. If any elements of the list are also
lists, the returned list should have the individual elements of
that nested list. If there no elements in the original list, return
an empty list. You can assume that the nested lists will not
contain any elements that are also nested lists. The elements of
the returned list should be in the same order of the original list.
Hint: using the built-in type() will be useful.
Test Cases:
>>> list1 =
flatten_list([True,"or",["Dare",88.8,False],"2",[3,5]])
>>> print(list1)
[True, 'or', 'Dare', 88.8, False, '2', 3, 5]
>>> list2 =
flatten_list(["CS",[1301.0,False,True],[100,0.0],"GTENS"])
>>> print(list2)
['CS', 1301.0, False, True, 100, 0.0, 'GTENS']
nestedlist.py:
from collections import Iterable
def flatten_list(list):
for item in list: #items in list
if isinstance(item, Iterable) and not isinstance(item, (str,
bytes)):
for sub_item in flatten_list(item): #sub items in sub list
yield sub_item
else:
yield item
#example list-1
list1 = [True,"or",["Dare",88.8,False],"2",[3,5]]
#printing list-1
print(list(flatten_list(list1)))
#example list-2
list2 =["CS",[1301.0,False,True],[100,0.0],"GTENS"]
#printing list-2
print(list(flatten_list(list2)))
Output Screenshots:

Language: Python Topic: Lists Function name : flatten_list Parameters : aList (list) Returns: final_list (list) Description...