Skip to content Skip to sidebar Skip to footer

How To Sort A List Of Lists Based On Length Of Inner List?

I want to sort a list of lists based on the length of the second item in the sublists, like this: Input: list = [['A', '1234', 'X'],['B', '12', 'X'],['C', '12345', 'X'],['D', '123'

Solution 1:

Using sort or sorted with custom key.

Ex:

data = [['A', '1234', 'X'],['B', '12', 'X'],['C', '12345', 'X'],['D', '123', 'X']]
data.sort(key=lambda x: len(x[1]), reverse=True)

or sorted

data = sorted(data, key=lambda x: len(x[1]), reverse=True)

print(data)

Solution 2:

You're almost there:

data = [['A', '1234', 'X'],['B', '12', 'X'],['C', '12345', 'X'],['D', '123', 'X']]

out = sorted(data, key=lambda item: len(item[1]), reverse=True)

print(out)
#[['C', '12345', 'X'], ['A', '1234', 'X'], ['D', '123', 'X'], ['B', '12', 'X']]

Note that you shouldn't name your list list, as this would shadow the name of the builtin function and lead to problems later...

Post a Comment for "How To Sort A List Of Lists Based On Length Of Inner List?"