Using a list of lists in a function (Working, just wanted to know)


#1



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


I understand what to do, just not why I do it.


When I return the results of the flatten function, it asks for you to .append() in the instructions, meaning it must work in some way. When I tried it out, it gave errors, when I then tried the code on the top it worked. I wish to know why it didn't take the append. Thanks :slight_smile:


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

print flatten(n) 

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

print flatten(n)


#2

to use append() you need two loops to get access the elements in the inner list

given you deal with multi-dimensional list, you need the first loop to get access to the inner list, the second loop to get access to the elements in the inner list


#3

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