Python Sorting Capabilities

by Matias Herranz

Custom sorting function as parameter to sorted() in Python

I am currently working with Python and I came across a list of image names which I’d like to sort. So, I call the sorted function with this list:

Unfortunately, it doesn’t work as well as I would have liked. So I asked myself: What can be done to sort the list as I want it to be sorted?

Python’s standard library sorted function, as you can see here, has an optional cmp parameter, through which one can pass a custom comparison function.

Going back to my example, I needed the images to be compared by the number in their name. For that reason I made this little function to achieve this goal:

And now let’s put all together:

TA DA!

Matias Herranz is as a Python Developer for Santex. He is a Computer Science and Open Source software enthusiast. His professional experience has focused on Python/Django web app development and some incursions in mobile apps for iPhone/Android. He is a team player who enjoys and finds it rewarding to share the things he learns, either through conferences and lectures, or through day-to-day communication with his coworkers.

  1. Hey Matias, nice post! Take into account the “cmp” parameter was replaced by “key” in Python3, thus is recommended to use it in Python2 to simplify further migrations. Regards!

  2. Thank you a lot for sharing this with all of us you actually realize what you are speaking about!
    Bookmarked. Kindly additionally consult with my web site =).

    We may have a link exchange arrangement among us

Comments are closed.