Why this code doesn't work?


#1

This is from python 12.Lists and Functions 18/18

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]

def flatten(a):
    c = []
    for r in range(0, len(a)):
        if r == 0:
            for e in range(0, len(a[r])):
                c.append(a[r][e])
            return c
        elif r == 1:
            for e in range(0, len(a[r])):
                c.append(a[r][e])
            return c
    return c




print flatten(n)

#2

Quite a few unnecessary operations, in your code. All you are required to do is flatten the list

[[ ]] to []

This can be achieved by looping through your 2d List and appending all the values to a new 1d List

c= []
for val in a:
    c += val
return  c

#3

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