Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python find list lengths in a sublist

Tags:

python

list

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!

like image 672
JBWhitmore Avatar asked Jan 09 '10 00:01

JBWhitmore


People also ask

How do I find the length of a list in a list?

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.

How do you count elements in a nested list in Python?

The len() built-in function of the LIST class can be used to count a number of elements in the list of lists.


6 Answers

map(len, a[0])

like image 168
Matthew Iselin Avatar answered Sep 30 '22 23:09

Matthew Iselin


[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]
like image 32
sberry Avatar answered Oct 02 '22 23:10

sberry


[len(x) for x in a[0]]
like image 44
John Machin Avatar answered Oct 02 '22 23:10

John Machin


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

[len(l) for l in a[0]]
like image 35
T. Stone Avatar answered Oct 02 '22 23:10

T. Stone


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;-).

like image 20
Alex Martelli Avatar answered Oct 04 '22 23:10

Alex Martelli


using the usual "old school" way

t=[]
for item in a[0]:
    t.append(len(item))
print t
like image 25
ghostdog74 Avatar answered Oct 02 '22 23:10

ghostdog74