Why do I not specify the list here?


#1




None


When creating the double loop and then appending the information from list A or B to results we only append the "num".
I have tried passing this excersice for over 20 minutes trying to append:
results.append(lst[num]) and that does not work.

Why does this not work ? How can giving more specific information as a argument lead to not working code ? What am I missing here.

Thanks.


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



print flatten(n)


#2

You code works perfectly for me. Try refreshing. Additionally,

you don't need to append that ^ just append num to results without the list[num] :slight_smile:


#3

Thanks for the quick reply.

I know my code works, but I am just wondering WHY it does not work when you specify the list. This was very confusing for me, and it was by accident that I discovered that it worked by just appending num.


#4

Well if you did this:

it would append the number in lst that was at the index of whatever num is. (That's hard to follow I know)
Say num was 2, lst[num] it would return 3 because the index two in lst is 3 (I think, it's a little confusing with the multi dimensional array as well as the for each loops)
Anyways, the point is that num is every number in both arrays.
When you say for lst in lists, there are two, lst 1, [1, 2, 3], and lst 2, [4, 5, 6, 7, 8, 9]. Looking at for num in lst, that's each number in both lists, 1, 2, 3, 4, 5, 6, 7, 8, 9. Appending num to results is appending every number so it's in one list.

I know this is a really rough explanation, but I hope that it helped.


#5

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