Using a list of lists in a function


#1



https://www.codecademy.com/courses/python-beginner-nzzVa/4/2?curriculum_id=4f89dab3d788890003000096

I get this error message "Oops, try again. flatten([[1, 2], [3, 4]]) returned [1, 2, 3, 4, 5, 6, 7, 8, 9] instead of [1, 2, 3, 4]" even though the black dialog box shows [1, 2, 3, 4, 5, 6, 7, 8, 9]


n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here
def flatten(lists):
    results = []
    for lists in n: 
        for numbers in lists: 
            results.append(numbers)
    return results 
       
print flatten(n)


#2

your function only works for a single list, this not very efficient. The great thing about function is that they can do the same task multiply times

What if you want to flatten another list:

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here
def flatten(lists):
    results = []
    for lists in n: 
        for numbers in lists: 
            results.append(numbers)
    return results 
       
print flatten(n)
print flatten([[1,2],[3,4]])

make your function work for more then 1 list


#3

4 posts were split to a new topic: Using a list in a function


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.