473,761 Members | 2,824 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Iterating through a nested list

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!

Apr 16 '06 #1
2 7786
On Sat, 15 Apr 2006 22:36:17 -0500, CamelR wrote:
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]


If you don't actually need the index of each item, don't use for i in
range(), just iterate over the list:

for obj in Array:
print obj

Notice that your list has two items, the first is a string and the second
is a sub-list. The natural way of proceeding would be:

for obj in Array:
for item in obj:
print item

but that gives too much: it iterates over the string, giving you
individual characters.

Instead, do this:

for obj in Array:
if isinstance(obj, list):
for item in obj:
print item
else:
print obj
which helps, but not enough: it only prints two levels down, and your data
has three. This time -- next time it might have two, or fifteen, or one...

Instead, create a helper function like this:

def walk(seq):
"""Walk over a sequence of items, printing each one in turn, and
recursively walking over sub-sequences.
"""
print seq
if isinstance(seq, list):
for item in seq:
walk(item)
Notice that this function calls itself.

This version of walk() prints the entire sequence at every level. Here is
a version which doesn't:

def walk2(seq):
if isinstance(seq, list):
for item in seq:
walk2(item)
else:
print seq
--
Steven.

Apr 16 '06 #2
In <pa************ *************** *@REMOVETHIScyb er.com.au>, Steven
D'Aprano wrote:
for obj in Array:
if isinstance(obj, list):
for item in obj:
print item
else:
print obj


I would "reverse" that check and test `obj` for not being a string::

for obj in Array:
if not isinstance(obj, basestring):
for item in obj:
print item
else:
print obj

This way it works with other types of iterables than lists too. Often
strings are the only type that one don't want to iterate over in such a
context.

Ciao,
Marc 'BlackJack' Rintsch
Apr 16 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1505
by: Brett | last post by:
I am trying to pass the value of a nested list into a function (to my "if" statement) as follows: textfilelist = "]] def idfer(listlength, comparelistlength, list): while x < (listlength - 1): while y < comparelistlength: if list == titlelist2: (I cutoff the end to focus on the problem)
4
7133
by: Lee K. Seitz | last post by:
I'm still relatively new to stylesheets. I'm trying to do something that seemed fairly simple on the surface, but is proving to be a challenge. I have a set of nested lists: <ul> <li>Side One</li> <ul> <li>Pac-Man Fever</li> <li>Froggy's Lament</</li> <li>Ode to a Centipede</</li>
11
15549
by: mlf | last post by:
Is there a clever way, or any way for that matter, to have a nested list show 1.1, 1.2, 1.3...2.1, 2.2, etc?
2
7590
by: alexandre_irrthum | last post by:
Hello, I'd like to apply a function to elements of a nested list and wondered if there is anything more idiomatic and/or shorter than this recursive way: >>> def recur_map(f, data): .... if isinstance(data, list): .... mapped_list = .... for i in data:
6
15418
by: deko | last post by:
How do I construct an XHTML-compliant nested unordered list? This displays correctly (both FF and IE): <ul> <li>list item</li> <li>list item</li> <li>list item</li> <ul> <li>nested list item</li>
7
3645
by: patrick j | last post by:
Hi I'm wondering about lists with nested lists as one does on a Saturday afternoon. Anyway below is an example of a list with a nested list which the iCab browser's very useful HTML verification ability will not like: <ul> <li><a href="#">link</a></li>
2
4082
by: torbs | last post by:
Hi I have expanded an suckerfish-type menu ( http://testwww.sogn.vgs.no?p=first ), but I have a problem with Internet Explorer. I believe it is because of the z-index-problem. Am I correct? Can anyone suggest a solution where nested list overlap? Why do the first list entry not overlap? I have used several hours on this problem. Normaly that means I will solve it tomorrow within the first five minuttes.
5
2397
by: Jyotirmoy Bhattacharya | last post by:
I'm a newcomer to Python. I have just discovered nested list comprehensions and I need help to understand how the if-clause interacts with the multiple for-clauses. I have this small program: def multab(n): print 'multab',n return print
2
11265
by: Gentr1 | last post by:
Hi everybody! I am presently working on a Genetic Programming API in python. I have a bit of a problem at the moment... For some specific reasons, I am using nested lists data structure to represent a tree. The first element of a list is always the head of the node, while all others represent the tail of the node. e.g. the nested list , E], ] represent the following tree: http://www.csd.abdn.ac.uk/~mkhoury/tree.jpg I need to be able...
3
2475
by: suneelkn | last post by:
Unable to identify the same level for nested lists in all scenarios, when the nested-list inside an ordered list the conversion process executes with out proper list order for nested list items. The Ordered / Un-ordered lists are not recognized in case of nested lists. Example: <ordered-list token="digit"> <item> <para>I Item of I</para> </item> <item> <para>Nested 1</para> <ordered-list token="uc-letter">
0
9554
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9377
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10136
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9989
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9925
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7358
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6640
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5266
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
3509
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.