TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Python List sort() method with Examples

Python List sort() method with Examples on append(), clear(), extend(), insert(), pop(), remove(), index(), count(), pop(), reverse(), sort(), copy(), all(), bool(), enumerate(), iter(), map(), min(), max(), sum() etc.

<< Back to PYTHON

Python List sort() Method

Python 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

Return

It 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 2

This 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 3

This 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




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf