18/18 code returning [1]?


#1

My code is as follows:

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

For some reason this returns [1] rather than the expected flattened list. What’s especially strange is that, upon copying and pasting code that is exactly the same aside from using larger tabs, the code works.

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



print flatten(n)

Am I just missing some minute difference that changes the output? I’ve compared the two over and over but can’t figure out what’s causing this. Thanks for any help on the matter.

Edit. After seeing the code as it appears in this post, they are identical. Note that in the interactive editor this is not the case. In the first code, the r in “results” appears directly under the f in “def”, while in the second code the r appears underneath the f in “flatten”. This is the only difference I can distinguish.


#2

the most likely way to achieve the first output is:

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

codecademy’s editor has sometimes trouble with displaying indent correctly.

but both codes you posted run fine and produce the same output.


#3

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