Tomáš Zato Tomáš Zato - 1 year ago 83
Python Question

Find index of longest sub-list in 2D list

I originally had two arrays, one contained numbers, the other associated values:

scores = [2, 4, 12 ... etc ]
players = ["Peter", "Brian", "Meg" ... etc]
top_score_index = scores.index(max(scores))
top_player = players[top_score_index]

This already stinks, because the
obviously iterates over that list twice (in the worst case scenario).

Situation changed, the
array now contains lists:

scores = [[something, something, something], [something, something]]

The score which I care about is however simply
len( scores[some_offset] )
, that is the length of nested list.

How can I easily find the index of longest of those nested lists? Eg. for:


I would expect return value of
. Please that efficiency is a concern for me right now.

cco cco
Answer Source
scores = [[0,0,0],[0,0],[0,0,0,0,0,0]]
print(max((len(l), i) for i, l in enumerate(scores))[1])

Prints 2.

You can't avoid calling len on each sublist, so I don't think you can do better as far as efficiency.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download