JBWhitmore
JBWhitmore

Reputation: 12316

Python find list lengths in a sublist

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

Answers (7)

divenex
divenex

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

T. Stone
T. Stone

Reputation: 19495

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

[len(l) for l in a[0]]

Upvotes: 3

ghostdog74
ghostdog74

Reputation: 343181

using the usual "old school" way

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

Upvotes: 1

Alex Martelli
Alex Martelli

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

Matthew Iselin
Matthew Iselin

Reputation: 10670

map(len, a[0])

Upvotes: 10

John Machin
John Machin

Reputation: 83032

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

Upvotes: 3

sberry
sberry

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

Related Questions