## DEV Community is a community of 877,885 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# How to sort a list in Python

In this post we will discuss how to sort list in Python.

There are mainly two ways to sort a list in Python.

1. `sorted` function
2. `sort` method

## 1. `sorted` function:

This sort the given list and generate a new list, which means existing list won't be modified.

``````In : numbers = [23, 42, 12, 121, 45, 9, 8]

In : sorted(numbers)
Out: [8, 9, 12, 23, 42, 45, 121]

In : numbers
Out: [23, 42, 12, 121, 45, 9, 8]
``````

As you can see in the above example `Out` has the same numbers list.

## 2. `sort` method:

This method applies the sorting on the list and updates the existing list. This is called in place sorting.

``````In : numbers.sort()

In : numbers
Out: [8, 9, 12, 23, 42, 45, 121]
``````

## Key param:

`sorted` and `sort` methods takes an extra parameter called `key`. Using this `key` param we can control the sorting.

Example: `names = ['Bob', 'Charles', 'James']`. Let's say we want to sort the above list of `names` based on length of the each time.
Solution:

``````In : sorted(names, key=len)
Out: ['Bob', 'James', 'Charles']
``````

We can pass any function we want to this `key`. Let me know which method you like in the comments. If you like this content consider following me.
{"ft_lang_label":"__label__en","ft_lang_prob":0.74834627,"math_prob":0.80987656,"size":1168,"snap":"2022-27-2022-33","text_gpt3_token_len":353,"char_repetition_ratio":0.12714776,"word_repetition_ratio":0.057142857,"special_character_ratio":0.34332192,"punctuation_ratio":0.21785714,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9525926,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-06-29T07:39:56Z\",\"WARC-Record-ID\":\"<urn:uuid:857653ba-40c2-405c-9892-33a1617c6ead>\",\"Content-Length\":\"89153\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:1a23fbc4-c413-4e51-86e5-e38aaf98ef2b>\",\"WARC-Concurrent-To\":\"<urn:uuid:0ed7bb31-41bd-4bcd-9788-3a45cabb9b56>\",\"WARC-IP-Address\":\"146.75.37.194\",\"WARC-Target-URI\":\"https://practicaldev-herokuapp-com.global.ssl.fastly.net/afizs/how-to-sort-a-list-in-python-2ok9\",\"WARC-Payload-Digest\":\"sha1:W5GH3XBWZYBGGKOYGAPTNA64W2WHFGGN\",\"WARC-Block-Digest\":\"sha1:I42EGVHXHSTAJ4ZQWBSKCAXDNCK3AXJP\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-27/CC-MAIN-2022-27_segments_1656103624904.34_warc_CC-MAIN-20220629054527-20220629084527-00679.warc.gz\"}"}