# Sort List of Integers in Python (2 Examples)

In this article, Iâ€™ll demonstrate how to sort a list of integers in Python.

The content of the page is structured as follows:

With that, hereâ€™s how to do it!

## Creation of Example Data

The following integer list will be used as the basis for this Python programming tutorial.

`integer_list = [5, 3, -87, 199, -3, 0]       # generating an example integer list`

## Example 1: Sorting with sort() Method

In this example, a list of integers is sorted with the sort() method.

```integer_list.sort()                          # sorting the list ascending
print(integer_list)                          # printing the sorted list
# [-87, -3, 0, 3, 5, 199]```

In the previous output, sorting is in ascending order. To sort the list in descending order, the reverse parameter should be set to True as follows.

```integer_list.sort(reverse=True)              # sorting the list descending
print(integer_list)                          # printing the sorted list
# [199, 5, 3, 0, -3, -87]```

You can see how the output above is in reverse order of the previous one.

## Example 2: Sorting by using sorted() Function

In this example, a list of integers is sorted using the sorted() function.

```print(sorted(integer_list))                  # sorting the list and printing
# [-87, -3, 0, 3, 5, 199]```

Unlike the sort() method, the sorted() function doesnâ€™t alter the original list. It creates a new sorted version of the original list and returns that as an output. See how the initial list is printed when one calls integer_list.

```print(integer_list)                          # printing integer_list
# [5, 3, -87, 199, -3, 0]```

Once again, to get the sorting in descending order, the reverse parameter has to be set to True as shown below.

```print(sorted(integer_list, reverse=True))    # sorting in reverse and printing
# [199, 5, 3, 0, -3, -87]```

Well done! We see two ways of sorting an integer list in Python.

## Video & Further Resources

In case you need further info on the examples of this tutorial, I recommend having a look at the following video on my YouTube channel. In the video instruction, Iâ€™m explaining the Python programming syntax of this article in Python.

Furthermore, you might want to read the related tutorials on my homepage:

To summarize: This article has shown how to create a sorted list of integers in the Python programming language. In case you have any further questions, donâ€™t hesitate to let me know in the comments section.

This page was created in collaboration with Ã–mer Ekiz. Have a look at Ã–merâ€™s author page to get more information about his professional background, a list of all his tutorials, as well as an overview of his other tasks on Statistics Globe.

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Top