C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Python List sort() MethodPython sort() method sorts the list elements. It also sorts the items into descending and ascending order. It takes an optional parameter 'reverse' which sorts the list into descending order. By default, list sorts the elements into ascending order. The examples and signature are given below. Signature
sort() Parameters
No parameter ReturnIt returns None. Let's see some examples of sort() method to understand it's functionality. Python List sort() Method Example 1
It is a simple example which sorts two lists in ascending order. See the example below.
# Python list sort() Method
# Creating a list
apple = ['a', 'p', 'p', 'l', 'e'] # Char list
even = [6,8,2,4] # int list
print(apple)
print(even)
# Calling Method
apple.sort()
even.sort()
# Displaying result
print("\nAfter Sorting:\n",apple)
print(even)
Output: ['a', 'p', 'p', 'l', 'e'] [6, 8, 2, 4] After Sorting: ['a', 'e', 'l', 'p', 'p'] [2, 4, 6, 8] Python List sort() Method Example 2This example sorts the list into descending order. # Python list sort() Method # Creating a list even = [6,8,2,4] # int list # Calling Method #apple.sort() even.sort(reverse=True) # sort in reverse order # Displaying result print(even) Output: [8, 6, 4, 2] Python List sort() Method Example 3This example sorts the char list into descending order.
# Python list sort() Method
# Creating a list
apple = ['a', 'p', 'p', 'l', 'e'] # Char list
even = [6,8,2,4] # int list
print(apple)
print(even)
# Calling Method
apple.sort(reverse=True)
even.sort(reverse=True)
# Displaying result
print("\nAfter Sorting:\n",apple)
print(even)
Output: ['a', 'p', 'p', 'l', 'e'] [6, 8, 2, 4] After Sorting: ['p', 'p', 'l', 'e', 'a'] [8, 6, 4, 2]
Next TopicPython Lists
|