Question

def flatten(1st): Takes a nested list and flattens it. >flatten([1, 2, 3]) [1, 2, 3] >>> x = [1, [2, 3], 4] >>> flatten (

Can you also explain the functions and what they do please?

0 0
Add a comment Improve this question Transcribed image text
Answer #1
def flatten(lst):
    if type(lst) != list:  # item lst is not of type list
        return [lst]  # then put it inside a list and return it
    result = []  # create empty list as result
    for item in lst:  # go through each item in list
        result += flatten(item)  # flatten the item recursively and add the list to result list
    return result  # return the result list


print(flatten([1, 2, 3]))
print(flatten([1, [2, 3], 4]))
print(flatten([[1, [1, 1]], 1, [1, 1]]))
print(flatten([1, [[2], 3], 4, [5, 6]]))

[1, 2, 3] [1, 2, 3, 4] [1, 1, 1, 1, 1, 1] [1, 2, 3, 4, 5, 6] Process finished with exit code 0

Add a comment
Know the answer?
Add Answer to:
Can you also explain the functions and what they do please? def flatten(1st): ""Takes a nested...
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
ADVERTISEMENT