Tomáš Zato Tomáš Zato - 19 days ago 5
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
scores.index(max(scores))
obviously iterates over that list twice (in the worst case scenario).

Situation changed, the
scores
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:

[[0,0,0],[0,0],[0,0,0,0,0,0]]


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

cco cco
Answer
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.