views:

230

answers:

6

I am trying to find out how to get the length of every list that is held within a particular list. For example:

a = []
a.append([])
a[0].append([1,2,3,4,5])
a[0].append([1,2,3,4])
a[0].append([1,2,3])

I'd like to run a command like:

len(a[0][:]) 

which would output the answer I want which is a list of the lengths [5,4,3]. That command obviously does not work, and neither do a few others that I've tried. Please help!

+11  A: 

[len(x) for x in a[0]] ?

>>> a = []
>>> a.append([])
>>> a[0].append([1,2,3,4,5])
>>> a[0].append([1,2,3,4])
>>> a[0].append([1,2,3])
>>> [len(x) for x in a[0]]
[5, 4, 3]
sberry2A
Depending on the size of your a[0] you may want to opt for Matthew Iselin's solution using map. In some cases (where lambda is not needed) map may be marginally faster. But that would only be for a very large a[0]
sberry2A
+1  A: 
[len(x) for x in a[0]]
John Machin
+1  A: 

This is known as List comprehension (click for more info and a description).

[len(l) for l in a[0]]
T. Stone
+4  A: 

map(len, a[0])

Matthew Iselin
A: 
def lens(listoflists):
  return [len(x) for x in listoflists]

now, just call lens(a[0]) instead of your desired len(a[0][:]) (you can, if you insist, add that redundant [:], but that's just doing a copy for no purpose whatsoever -- waste not, want not;-).

Alex Martelli
A: 

using the usual "old school" way

t=[]
for item in a[0]:
    t.append(len(item))
print t
ghostdog74