Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Sort 2-Dimensional Array by Array length?

Sorry I have to ask, but I looked around for quite a while, finding nothing helpful.

Here's the problem; I have a list of Arrays:

list = [["I","Am"], ["An","Array", "Within", "An Array"]]

I want to sort "list" by the length of the Arrays it contains.

Sofar I've tried:

list.sort()

#and
def nc(x):
    return len(x)

list.sort(key=nc)

But these both return "None". I would truly appreciate some help with this. Thank you in advance!

like image 874
user2388026 Avatar asked Feb 15 '23 12:02

user2388026


1 Answers

a_list.sort() results a_list to be sorted in place (modifying itself) and returns None as it is designed.

sorted( a_list, key=len ) will return the sorted list.

BTW your input data is already sorted, what was the expected result?

like image 98
Jokester Avatar answered Feb 17 '23 00:02

Jokester