Iterating through a nested list

CamelR thecamel at camelrichard.org
Sat Apr 15 23:36:17 EDT 2006


I have a newbie question, and I have seen reference to this mentioned
in many places, but all just say "this has been discussed frequently
in (other places) so we won't discuss it here..." and I am unable to
find the actual answer...

I expected :

Array = ["topdir", ["/subdir1", ["/file1", "/file2"], "/subdir2",
["/file1", "/file2"], "/subdir3", ["/file1", "/file2"]]]

for i in range(len(Array)):
  print Array[i]
  for x in range(len(Array[i])):
    print Array[i][x]
    for y in range(len(Array[i][x])):
      print Array[i][x][y]

to produce output like this:

topdir
['/subdir1', ['/file1', '/file2'], '/subdir2', ['/file1', '/file2'],
'/subdir3', ['/file1', '/file2']]
/subdir1
['/file1', '/file2']
/file1
/file2
/subdir2
['/file1', '/file2']
/file1
/file2
/subdir3
['/file1', '/file2']
/file1
/file2

but instead, it is iterating through each character in the elements,
like this:

topdir
t
t
o
o
p
p
d
d
i
i
r
r
['/subdir1', ['/file1', '/file2'], '/subdir2', ['/file1', '/file2'],
'/subdir3', ['/file1', '/file2']]
/subdir1
/
s
u
b
d
i
r
1
['/file1', '/file2']
/file1
/file2
/subdir2
/
s
u
b
d
i
r
2
['/file1', '/file2']
/file1
/file2
/subdir3
/
s
u
b
d
i
r
3
['/file1', '/file2']
/file1
/file2


so what am I doing wrong?  I would really appreciate any advice or
pointers...  

Thanks!




More information about the Python-list mailing list