Lesson 18: Lists and Functions, need help?


#1

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

When I try to use this code:

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(numbers)
    return results

print flatten(n)

I get this error message: Oops, try again. flatten([[1, 2], [3, 4]]) returned [[1, 2], [1, 2], [3, 4], [3, 4]] instead of [1, 2, 3, 4]

I have been stuck for a while and am unsure of what I am doing wrong. Please help, thanks.


#2

In line 7,
try to replace the variable "numbers" with "item" which you declared
which should be:

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)

here we got a double for-loop
in the first run of the outer loop, we will get: [1, 2, 3]
then we'll jump into the inner loop which will then get [1] in the first run of the inner loop
then [2] in the second run and [3] of course for the third.
these three integer were saved in the "item" variable rather than "numbers" var in line 6
so what you should do is to append the integer saved in "item" into "results" list.

Hope this explanation would help :smiley:


#3

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