List recursion?

52 Views Asked by At

I wrote a function:

def expandList(aList):
    """expand a list"""

    finalList = []

    for j in aList:
        tempList = []

        if type(j) != type(list):
            tempList.append(j)
            finalList.extend(tempList)

        else:
            finalList.extend(expandList(j))

    return finalList

to expand nested list within themselves like:

[[1, [2, 3], [3, 2]], [2, [1, 3], [3, 1]], [3, [1, 2], [2, 1]]]

into:

[[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]

or

    [[1, [2, [3, 4], [4, 3]], [3, [2, 4], [4, 2]], [4, [2, 3], [3, 2]]], 
[2, [1, [3, 4], [4, 3]], [3, [1, 4], [4, 1]], [4, [1, 3], [3, 1]]], 
[3, [1, [2, 4], [4, 2]], [2, [1, 4], [4, 1]], [4, [1, 2], [2, 1]]], 
[4, [1, [2, 3], [3, 2]], [2, [1, 3], [3, 1]], [3, [1, 2], [2, 1]]]]

into:

[[1, 2, 3, 4],[1, 2, 4, 3],[1, 3, 2, 4],
[1, 3, 4, 2],[1, 4, 3, 2],[1, 4, 2, 3],[2, 1, 3, 4],
[2, 1, 4, 3],[2, 3, 1, 4],[2, 3, 4, 1],[2, 4, 1, 3],
[2, 4, 3, 1],[3, 1, 2, 4],[3, 1, 4, 2],[3, 2, 1, 4],
[3, 2, 4, 1],[3, 4, 1, 2],[3, 4, 2, 1],[4, 1, 2, 3],
[4, 1, 3, 2],[4, 2, 1, 3],[4, 2, 3, 1],[4, 3, 1, 2], 
[4, 3, 2, 1]]

and so forth. I wish to be able to do this in any size of nested lists.


My function doesn't seem to work right. What am I doing wrong? How can I fix/improve my function?

Thank you in advance

1

There are 1 best solutions below

2
On

First of all using following command is a wrong way for checking the list type :

type(j) != type(list)

because type(list) returns <type 'type'> actually you are getting the type of a type object that is a type.

In edition you don't need to loop over your sub list and using extend method although you used it incorrect.Since your numbers are in the first index you can just convert it to list and append the rest to it.

You can use a simple list comprehension :

>>> [[[i[0]]+j for j in i[1:]] for i in l]
[[[1, 2, 3], [1, 3, 2]], [[2, 1, 3], [2, 3, 1]], [[3, 1, 2], [3, 2, 1]]]