18. Using a list of lists in a function

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)

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)

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)

Sorry code won’t indent for some reason.

You should use the option into the text editor Preformatted Text

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)
1 Like

SRELUN

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

@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?.

@maemoazzam, Thanks!

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