0

Possible Duplicate:
Flatten (an irregular) list of lists in Python

Hi I was working out with nested lists in python and found this to be a big problem. I know we should go with recursive functions but unable to proceed..

Community
  • 1
  • 1

2 Answers2

1

If you have list of list -e.g max depth is 1 then you can use the following code:

lVals = [1,[2,3]]

res = []
for i in lVals:
    if isinstance(i, list):
        res.extend(i)
    else:
        res.append(i)

print res
>>> [1,2,3]
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52
0
def flatten(li):
    if not isinstance(li, list):
        return [li]
    rv = []
    for ll in li:
        rv.extend(flatten(ll))
    return rv


print flatten([1,2,3,4])
print flatten([1,[2,3],3,4])
print flatten([1,[2,[3,4,5]],3,4])
print flatten([1,[2,[3,4,5]],3,[]])

gives

[1, 2, 3, 4]
[1, 2, 3, 3, 4]
[1, 2, 3, 4, 5, 3, 4]
[1, 2, 3, 4, 5, 3]
rocksportrocker
  • 7,251
  • 2
  • 31
  • 48