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!
There is a built-in function called len() for getting the total number of items in a list, tuple, arrays, dictionary, etc. The len() method takes an argument where you may provide a list and it returns the length of the given list.
The len() built-in function of the LIST class can be used to count a number of elements in the list of lists.
map(len, a[0])
[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]
[len(x) for x in a[0]]
This is known as List comprehension (click for more info and a description).
[len(l) for l in a[0]]
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;-).
using the usual "old school" way
t=[]
for item in a[0]:
t.append(len(item))
print t
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With