2009/3/11 Emad Nawfal (عماد نوفل) <emadnaw...@gmail.com>: > Now I know that I did not ask the right question. What I meant was: how to > extract a sublist from a list whose length is unknown. Let's say I have a > hundred of these lists and each of these has an NP somewhere, it could be > nested in nested list, which is turn nested in another one and so on. The > bottom line is that I do not know the index. To make things more concrete, > this is a representative list. How can I extract all the sublists beginning > with "NP" from it?
You'll have to do recursion - that is: NPstart(alist) = if alist starts with "NP": alist + NPstart for all sublists of alist else: NPstart for all sublists of alist Turning that into Python we get: def NPstart(alist): if isinstance(alist, basestring): # It's ugly to do an isinstance in Python, but any better method would be fully changing your data structure, so I use it for now return [] else: if alist[0] == 'NP': return [alist] + [NPstart(sublist) for sublist in alist] else: return [NPstart(sublist) for sublist in alist] -- André Engels, andreeng...@gmail.com _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor