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
First of all using following command is a wrong way for checking the list type :
because
type(list)
returns<type 'type'>
actually you are getting the type of a type object that is atype
.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 :