Help me understand why this is correct please!


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

print flatten(n)

why this is correct?


why wouldn't it be? Apart from using range() which complicates your code, given it gives you indexes rather then the values from the list, its valid


So n is a list with lists inside. The objective is to get it into one list.

So what is flatten() doing, let's assume we pass n to it?
First it creates an empty list and assigns it to results.

In the first for statement let's look at what range(len(lists)) is doing. len(lists) is looking at how many items there is in the variable lists. In this case lists is n, which has two items in it, each item is another list. So that becomes, in effect range(2), which is the same as [0, 1], which are the index positions in lists. So the first if statement is for i in. [0,1]:

This brings us to the second for statement. It is doing exactly the same as the first if statement however this time rather than len(lists) it is looking at the index positon in lists, with the index position being denoted by i. So for the first iteration it would be for j in range(len(n[0])):
n[0] is [1,2,3] so len(n[0]) is 3. range(3) is [0,1,2] which are the index positions for the list in n[0]. So it becomes for j in [0,1,2]:

So lastly, results.append(lists[i][j]).
results is our empty list from the start. append is a way to add items to the results list. What are we adding to results then?

Let's assume we are on the first loop of both for statements.
We are adding n[0][0]. Let's roll back, what is n[0]? That is the list [1,2,3]. The second [0] is the index position in the list [1,2,3], which would be 1. n[0][1] would be 2 and n[0][2] would be 3.

results would be [1,2,3,4,5,6,7,8,9] at the end of all loops.

So long story short the function is going into each nested list in the main list and adding each value in the nested list to a new list called results. As such it returns a list with no nested lists.

If there was another level of lists within n, i.e. [[[1,2,],[3,4]],[[5,6],[7,8]]] then this function would not output a completely flattened list.


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