18. using a list of lists in a function


#1




Code does not behave incorrectly but I want clarification on something. How would I go about using the .append() function for this problem. I tried it and it gives back expectedly exactly what is put into the function. If you put in [1,2,3] it appends that to the new list. The exercise seemingly hints at using it but I found that it was easier to use += to append the list.



#3

for append to work, we need a double loop, if we have a single loop:

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

i will just hold the lists nested inside n (as you can see if you run the above code)

if you however use a double loop:

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

you will get access to the inner lists, then you can use append :slight_smile:


#4

Ah that makes sense. Thanks.


#5

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