Reputation: 12316
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!
Upvotes: 13
Views: 26341
Reputation: 17256
Matthew's answer does not work in Python 3. The following one works in both Python 2 and Python 3
list(map(len, a[0]))
Upvotes: 0
Reputation: 19495
This is known as List comprehension (click for more info and a description).
[len(l) for l in a[0]]
Upvotes: 3
Reputation: 343181
using the usual "old school" way
t=[]
for item in a[0]:
t.append(len(item))
print t
Upvotes: 1
Reputation: 882771
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;-).
Upvotes: 2
Reputation: 132138
[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]
Upvotes: 21