0

I am writing a helper function for flattening lists where i just remove the extra outer lists surrounding an integer:

def rem_list(a):
    if type(a) != list:
        print a,"about to return"
        return a
    else:
        rem_list(a[0])
a = []
lis2 = [2,4,[[2]],[[[1]]], 5, 6, [7]]
for each in lis2:
    a.append(rem_list(each))
print a

I am getting the output as follows:

2 about to return
4 about to return
2 about to return
1 about to return
5 about to return
6 about to return
7 about to return
[2, 4, None, None, 5, 6, None]

I do not understand this. I am returning an integer in each iteration to rem_list() but its returning None when there are outer lists present around the character. I have also included a print statement which checks exactly what I am about to return and it outputs correctly in the print but still returns None. Plz help.

niemmi
  • 17,113
  • 7
  • 35
  • 42
  • 6
    `return rem_list(a[0])` ? – polku Jul 12 '16 at 08:04
  • just add return to rem_list(a[0]), at the end of the recursion you are not returning anything – edt Jul 12 '16 at 08:13
  • Your solution won't work with such lists: `[2, 4, [[2, 8]], [[[1, 9, 0]]], 5, 6, [7]]`. Please look at [the following answer](http://stackoverflow.com/a/10824420/6551577). – Alex M Jul 12 '16 at 08:15

0 Answers0