tags:

views:

91

answers:

5

I have created a list ->

a = [[1,2,3],[4,5,6],[7,8,9]]

1) How do I get the count of number of sub-lists in a? Like in this case it is 3

2) I am using iterator tool chain for traversing this list

 for elt in itertools.chain.from_iterable(node):

Is there any way to know if I have traversed a sub list ?

+1  A: 

as with any other list:

>>> len(a)
3

pythonic way to count sub-lists in a heterogeneous list would be:

>>> sum(isinstance(i, list) for i in a)
3

your second question is not clear. can you not read your code?

SilentGhost
I can read my code I want to know when I have traversed a sub list...like after elements 1,2,3 then after 4,5,6
Bruce
@Peter: that's unintelligible. Please, ask another question with detailed explanation and example of what you're trying to achieve.
SilentGhost
A: 

1) len(a) is 3.

Ned Batchelder
A: 

The number of sub-lists is

len(a)

Each sublist is an element in the list, so you've got three elements in a, each of them is a list with three elements (which are numbers)

Khelben
A: 

if different types are stored in a list you can could sublists this way:

n=0
for b in a:
    if type(b)==type([]):
        n+=1

addition:

yes, sum(1 for x in a if isinstance(x, list)) is more pythonic

Antony Hatchkins
+2  A: 

1) sum(1 for x in a if isinstance(x, list))

This assumes that there could be things other than lists in a.

2) No. Delegating to itertools generally means you give up knowing anything about the underlying values.

Ignacio Vazquez-Abrams
wrong code: you need to sum integers
SilentGhost
I think you mean "sum(1 for x in a if isinstance(x,list))". Or "len(filter(lambda x:isinstance(x,list), a)" for that matter.
Tim Lesher
Yes, fixed now.
Ignacio Vazquez-Abrams
Don't you need [brackets] for list-creation syntax? ie. sum([1 for x in a if isinstance(x, list)])
BlueRaja - Danny Pflughoeft
I'm using a generator expression, not a list comprehension.
Ignacio Vazquez-Abrams