Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
List of strings in Python
Next article icon

How to sort a list of strings in Python

Last Updated : 19 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will explore various methods to sort a list of strings in Python. The simplest approach is by using sort().

Using sort() Method

The sort() method sorts a list in place and modifying the original list directly.

Python
a = ["banana", "apple", "cherry"]  # Sorting list in place a.sort() print(a) 

Output
['apple', 'banana', 'cherry'] 

Explanation:

  • a.sort() sorts the original list by modifying it.
  • Strings are sorted lexicographically (dictionary order).

Table of Content

  • Using sorted() Function
  • Sorting in Reverse Order
  • Case-Insensitive Sorting
  • Sorting by String Length
  • Sorting using Custom Key

Using sorted() Function

The sorted() function returns a new sorted list containing all the items from the original list.

Python
a = ["banana", "apple", "cherry"]  # Sorting the list res = sorted(a) print(res) 

Output
['apple', 'banana', 'cherry'] 

Explanation:

  • sorted(a) creates a new sorted list without modifying the original a.
  • Strings are sorted lexicographically (dictionary order).

Note: The main difference between sort() and sorted() is that sort() modifies the list in place without returning a new list, while sorted() creates a new sorted list from any iterable without modifying the original.

Sorting in Reverse Order

To sort strings in descending order, we can use the reverse=True parameter.

Python
a = ["banana", "apple", "cherry"]  # Sorting in reverse order res = sorted(a, reverse=True) print(res) 

Output
['cherry', 'banana', 'apple'] 

Case-Insensitive Sorting

String sorting in Python is case-sensitive by default. To perform a case-insensitive sort, we can use the key=str.lower parameter in sorted() function.

Python
a = ["Banana", "apple", "Cherry"]   res = sorted(a, key=str.lower) print(res) 

Output
['apple', 'Banana', 'Cherry'] 

Explanation: key=str.lower ensures that sorting is performed based on lowercase equivalents of strings.

Sorting by String Length

We can sort a list of strings by their lengths using the key=len parameter in sorted() function.

Python
a = ["banana", "apple", "kiwi"]  # Sorting by length res = sorted(a, key=len) print(res) 

Output
['kiwi', 'apple', 'banana'] 

Explanation: key=len sorts the strings based on their length in ascending order.

Sorting using Custom Key

We can also use any custom sorting logic using a key function.

Python
a = ["banana", "apple", "cherry"]  # Sorting by last character res = sorted(a, key=lambda s: s[-1]) print(res) 

Output
['banana', 'apple', 'cherry'] 

Explanation: lambda s: s[-1] extracts the last character of each string for comparison.



Next Article
List of strings in Python

S

Shivam_k
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • python-list
  • python-string
Practice Tags :
  • python
  • python-list

Similar Reads

  • Python | Sort each String in String list
    Sometimes, while working with Python, we can have a problem in which we need to perform the sort operation in all the Strings that are present in a list. This problem can occur in general programming and web development. Let's discuss certain ways in which this problem can be solved. Method #1 : Usi
    4 min read
  • Python | Sort list of dates given as strings
    To sort a list of dates given as strings in Python, we can convert the date strings to datetime objects for accurate comparison. Once converted, the list can be sorted using Python's built-in sorted() or list.sort() functions. This ensures the dates are sorted chronologically. Using pandas.to_dateti
    3 min read
  • Python | Sort all sublists in given list of strings
    Sorting sublists in a list of strings refers to arranging the elements within each sublist in a specific order. There are multiple ways to sort each list in alphabetical order, let's understand each one by one. Using list comprehensionList comprehension with sorted() allows efficient sorting of each
    2 min read
  • Sort Numeric Strings in a List - Python
    We are given a list of numeric strings and our task is to sort the list based on their numeric values rather than their lexicographical order. For example, if we have: a = ["10", "2", "30", "4"] then the expected output should be: ["2", "4", "10", "30"] because numerically, 2 < 4 < 10 < 30.
    2 min read
  • List of strings in Python
    A list of strings in Python stores multiple strings together. In this article, we’ll explore how to create, modify and work with lists of strings using simple examples. Creating a List of StringsWe can use square brackets [] and separate each string with a comma to create a list of strings. [GFGTABS
    2 min read
  • Create a List of Strings in Python
    Creating a list of strings in Python is easy and helps in managing collections of text. For example, if we have names of people in a group, we can store them in a list. We can create a list of strings by using Square Brackets [] . We just need to type the strings inside the brackets and separate the
    3 min read
  • How To Sort List Of Strings In Alphabetically
    When working with Python programs, be it any machine learning program or simple text processing program, you might have come across a need to sort a list of strings alphabetically, either in ascending or reverse order. Strings are sorted alphabetically based on their initial letter (a-z or A-Z). But
    3 min read
  • Python | Alternate Sort in String list
    Sometimes, while working with Python list, we can have a problem in which we need to perform sorting only of alternatively in list. This kind of application can come many times. Let's discuss certain way in which this task can be performed. Method : Using join() + enumerate() + generator expression
    2 min read
  • Tokenizing Strings in List of Strings - Python
    The task of tokenizing strings in a list of strings in Python involves splitting each string into smaller units, known as tokens, based on specific delimiters. For example, given the list a = ['Geeks for Geeks', 'is', 'best computer science portal'], the goal is to break each string into individual
    2 min read
  • Custom Sorting in List of Tuples - Python
    The task of custom sorting in a list of tuples often involves sorting based on multiple criteria. A common example is sorting by the first element in descending order and the second element in ascending order. For example, given a = [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)], sorting the tuples by t
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences