18. Using a list of lists in a function


#1

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

Oops, try again. flatten([[1, 2], [3, 4]]) returned [1, 2] instead of [1, 2, 3, 4]

I don't understand why I am getting this error, the code seems right to me.

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]

def flatten(lists):
    results = []
    for numbers in lists:
        for item in numbers:
            results.append(item)
        return results

print flatten(n)

#2

The line of code in which it says return results is indented to much.

Indent it back once and try it. Your code should look like this:

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]

def flatten(lists):
results = []
for numbers in lists:
for item in numbers:
results.append(item)
return results

print flatten(n)


#3

Here is the code indented:

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
results = []
for numbers in lists:
for item in numbers:
results.append(item)
return results

print flatten(n)


#4

Sorry code won't indent for some reason.


#5

You should use the option into the text editor Preformatted Text


#6

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

#7

SRELUN

maemoazzam is correct. back up your return statement so that it is in inline with the first for statment and it will run


#8

@maemoazzam ,

It is important to format code when you post it. That enables users to see your indentation and other important details.

To learn how to do it, see How do I format code in my posts?.


#9

@maemoazzam, Thanks!


#10

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