Using a list of lists in a function


#1



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


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


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

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



print flatten(n)


#2

The issue is the indentation on your return statement. You want to return the result of the original for loop, and currently you're returning the result of the lower nested one.

I struggled a bit to understand why this is, and you can skip this if you aren't interested, but the reason that's an issue is because your nested for loop is iterating through the the "higher" list, which will return the two lists themselves, brackets and all; in other words, you're returning a list of two lists. The second for loop is then iterating through those two lists themselves, returning the values within the lists.


#3

Once the return statement is in the correct place your code should work as expected. Good work.

Did you know that Python lets us concatenate lists? It does.

[9,8,7] + [6,5,4,3,2,1]    # [9, 8, 7, 6, 5, 4, 3, 2, 1]

This is especially handy if, like your solution, we do not have a limit on how many lists are contained.

>>> def flatten(list_of_lists):
    n = list_of_lists[0]
    for row in range(1, len(list_of_lists)):
        n += list_of_lists[row]
    return n

>>> flatten([[1, 2, 3], [4, 5, 6, 7, 8, 9]])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

Keep your code as a submission. It is important practice code. Just keep this concept (list concatenation) in the back of your mind for future use.


#4

hi, i like this code concept


#5

So, just so I'm clear, what exactly does append() do? and how does it work in this particular situation?


#6
List.append(element_to add)

As we can see above, append is a method of the List class that adds a new element to the end of the list. It's companion method is insert which inserts a new element to the front of the list if no index is given, else it inserts before the specified index.

https://docs.python.org/2/tutorial/datastructures.html


#7

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