18. Using a list of lists in a function


#1

Task:

Create a function called flatten that takes a single list and concatenates all the sublists that are part of it into a single list.

1 On line 3, define a function called flatten with one argument called lists.
2 Make a new, empty list called results.
3 Iterate through lists. Call the looping variable numbers.
4 Iterate through numbers.
5 For each number, .append() it to results.
6 Finally, return results from your function.

My code:

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

Error:

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

Question:

I dont know how it's possible to do task exactly correct, but in return got errors...


#2

oh, nevermind.
Sorry.

Right code:

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



print flatten(n)

#3

Great work! Is there anyway you can explain to me why 2 for loops work in this case. I am missing something important and feeling lost


#4

Well... When i used one "for" loop, i get the same lists ([1,2], [3,4]).

Then I gone mad, almost drop coding, etc.

Then I tryed to use second "for" loop, becouse if one loop returns two different list ([1,2], [3,4]). second "for" loop must iterate through all elements in two lists.


#5

The description:"For each number, add it to result." is confused for me.
Please try result = result + numbers[i] instead of result.append(numbers)
Thank you


#6

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