In this article we will discuss how to sort a list of string by,

• By Alphabetical Order
• By Reverse Alphabetical Order
• By String Length
• By Numeric Order

### list.sort()

list provides a member function sort(). It Sorts the elements of list in low to high order i.e. if list is of numbers then by default they will be sorted in increasing order. Whereas, if list is of strings then, it will sort them in alphabetical order.

Suppose we have a list of strings i.e.

Let’s sort this list of strings in different way i.e.

## Sort a List of strings in Alphabetical Order

It will sort the list in alphabetically i.e.

## Sort a List of strings alphabetically in Reverse Order

list.sort() accepts an another argument reverse. By default its value is False, but if its set to True then it will sort the list in reverse order.

So, contents of list will be now,

## Sort a List of string by Length

list.sort( key=function )

list.sort() accepts an another argument key i.e. key Function. While sorting a list, all the elements of list will be compared with each other. Before comparison it will call the key function on each entry,  to determine what should be compared.

For example,

To Sort a list of strings by length, provide len() as key function in sort i.e.

Now list contents will be,

## Sort a List of string by Numeric Order

Suppose w e have a list of strings that contains numbers i.e.

To Sort a this list of strings by Numeric Order, provide int() as key function in sort i.e.

Now list contents will be,

### Sorting a list of strings by Numerically in descending Order

To Sort in Descending numeric order, pass reverse flag along with key function i.e.

Now list contents will be,

Complete example is as follows,

Output:

• #### Best books to learn C++11

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,