Question

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

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']

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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:

Add a comment
Know the answer?
Add Answer to:
Language: Python Topic: Lists Function name : flatten_list Parameters : aList (list) Returns: final_list (list) Description...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT