Linux

# Guide to Sort a List with Python Sort List() Command

[ad_1]

We have a list of numbers or strings, and we want to sort the items in this list. Basically, we can either use sort method or sorted function to achieve what we want.

The difference between sort and sorted is that sort is a list method that modifies the list in place and we can’t use sort method with another object like tuple whereas sorted is a built-in function that creates a new list and the original one didn’t change.

In this article, we will mention how to use these functions to sort, in an ascending or descending manner, a list of numbers, strings, tuples, or literally any object.

We will also mention how to define your own custom sort functions.

## 1) Sorting a list of numbers

By `sort` method, we can sort list of numbers whether integer or float.

Note: the method comes after the object as example below

```  >>> Lst = [20, 25.4, 12, -16, -3.14, 3, -5, 7]
>>> Lst.sort()
>>> Lst
[-16, -5, -3.14, 3, 7, 12, 20, 25.4]
```

As you see the order of the object `Lst` has been changed.

But if we want to keep the original list without changing and assigns the new order to new list, we will use `sorted` function as below.

```  >>> Lst = [20, 25.4, 12, -16, -3.14, 3, -5, 7]
>>> Sorted_Lst = sorted(Lst)
>>> Sorted_Lst
[-16, -5, -3.14, 3, 7, 12, 20, 25.4]
```

If we want to sort the list in a descending order, we will use keyword `reverse` and assigning to it `True` as below.

```  >>> Lst = [20, 25.4, 12, -16, -3.14, 3, -5, 7]
>>> Sorted_Lst = sorted(Lst, reverse = True)
>>> Sorted_Lst
[25.4, 20, 12, 7, 3, -3.14, -5, -16]
```

## 2) Sorting a list of strings

We will use `sort` or `sorted` for sorting strings

```    >>> Lst = ['bmw','ford','audi','toyota']
>>> Lst.sort()
>>> Lst
['audi', 'bmw', 'ford', 'toyota']
```

Also we still use the `reverse` keyword to sort in a descending order.

```    >>> Lst = ['bmw','ford','audi','toyota']
>>> Lst.sort(reverse=True)
>>> Lst
['toyota', 'ford', 'bmw', 'audi']
```

Note: Python treats all uppercase letters before lowercase letters

We will see that on the example below.

```    >>> Lst = ['bmw','ford','audi','Toyota']
>>> Lst.sort()
>>> Lst
['Toyota', 'audi', 'bmw', 'ford']
```

But we can sort a list of strings in a case insensitive manner by using keyword `key=str.lower` for `sort` method as below.

```    >>> Lst = ['bmw','ford','audi','Toyota']
>>> Lst.sort(key=str.lower)
>>> Lst
['audi', 'bmw', 'ford', 'Toyota']
```

## 3) Sorting a list of tuples

We should know that tuple is immutable object when list is mutable object, also when we sort two tuples, we start out by comparing the first elements of the tuples and if they are not equal, this is the result of the comparison.

```    >>> (5, 7) >> (5, 7) > (5, 9)
False
```

Of course we can use `sort` method or `sorted` function for sorting tuples as below.

```    >>> sorted([(5, 4), (3, 3), (3, 10)])
[(3, 3), (3, 10), (5, 4)]
```
```    >>> sorted([('watermelon', 'green'), ('apple', ''), ('banana', '')])
[('apple', ''), ('banana', ''), ('watermelon', 'green')]
```

Note: We can sort tuple by second element

we will use `lambda` to define our own key function as below.

```    >>> Lst = [("Amanda", 35), ("John", 30), ("Monica", 25)]
>>> Lst.sort(key=lambda x: x)
>>> print(Lst)
[('Monica', 25), ('John', 30), ('Amanda', 35)]
```

## 4) Sorting a list of objects

Objects are type of data types for Python, to sort this type of data type, we should put this objects in a list as below.
Assume we have a `Student` class has name and age methods that looks like this:-

```    class Student:
def __init__(self, name, age):
self.name = name
self.age = age
```

Now we will create some `Student` objects and add them to a list for sorting them.

```    >>> John = Student('John', 30)
>>> Amanda = Student('Amanda', 35)
>>> Monica = Student('Monica', 25)
>>> Lst = [John, Amanda, Monica]
```

If we sort the list upon `name` method.

```    >>> Lst.sort(key=lambda x: x.name)
>>> print([item.name for item in Lst])
['Amanda', 'John', 'Monica']
```

If we sort the list upon `age` method.

```    >>> Lst.sort(key=lambda x: x.age)
>>> print([item.name for item in Lst])
['Monica', 'John', 'Amanda']
```

Python has many built-in functions and methods helping us to solve problems,`sort` and `sorted` are used to sort any list of numbers, strings, tuples and objects.

[ad_2]

Close