Python sort list (Array) | sorted function – Strings (alphabetically), Number, list

Python sort() function is used to sorts the elements of a given list. It sorts the list ascending, descending, or user-defined order where ascending order is by default.

Note:

  1. Ascending order is by default in sort() method.
  2. It changes the original list and doesn’t return any value.

Syntax

Parameter Values

Both parameter are Optional.

  • reverse:- if reverse = True will sort the list descending else as Default is (reverse=False)
  • key:- A function to specify the sorting criteria(s)

Python sort list using sort function example

1. Sort the list “Ascending” order:

Numbers

Output: [1, 2, 3, 4, 5]

Strings

Example of how to python sort list of strings.

Output:

2. Sort the list “descending” order

Use and Set the parameter reverse=True sorts the list in the descending order.

Output: [5, 4, 3, 2, 1]

Q: How to sort the list of lists in python?

Answer: If you want to sort on more entries, just make the key function return a tuple containing the values you wish to sort on in order of importance. For example:

Complete example

Output: [[7, 8, 9], [14, 25, 46], [1, 22, 53]]

Q: How to sort the list alphabetically in Python?

Answer: Use The sorted() function returns a sorted  list where Strings are sorted alphabetically.

Output: [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’]

Do comment if you have any doubts, something missing (you think must cover here), and suggestions on this tutorial.

Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.