Customize sort method for array
The sorting key is a function that, given a list element, returns a value that Python knows how to compare natively. For example, Python knows how to compare integers and strings.
Python can also compare tuples and lists that are composed of things it knows how to compare. The way tuples and lists get compared is that earlier items in the tuple or list take precedence over later values, just as you would expect.
In your case, you would want to make the following key function:
lambda name: (name[0], -len(name), name)
Items with smaller keys always come earlier in a sorted list. Thus, a smaller initial character causes an animal to come earlier. If two names have the same initial, a longer name length causes an animal to come earlier because the negative name length is smaller. Finally, if two animals’ names have the same initial and the same length, the tie is broken by lexicographic order.
This program demonstrates how to sort a list with the above key function:
animals = ["ant", "antelope", "zebra", "anteater", "cod", "cat"]
animals.sort(key=lambda name: (name[0], -len(name), name))
print(animals)