Python sort list of strings | Alphabetically & Number

Task: You have a list of strings and you have to sort it. There can be multiple scenarios possible while sorting a list of a sting in python, like:-

  • Sorting in alphabetical/reverse order.
  • Sort list of strings with numbers
  • Based on the length of string character

Let’s see one by one every possible scenarios examples.

How to Python sort list of strings?

Answer: You can use sort() or sorted function for it:-

Using sort() function Example

Output: [‘Alpha’, ‘Beta’, ‘Gama’, ‘Thor’, ‘Tony’, ‘Zuba’]

Using sorted() function Example

Output: [‘Alpha’, ‘Beta’, ‘Gama’, ‘Thor’, ‘Tony’, ‘Zuba’]

Python sort list of strings with numbers

Answer: Let’s see 2 example first integer string and then string with number.

List of Integer String (Sort numeric strings)

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

String with Numbers

Perhaps you are looking for human sorting (also known as natural sorting):

Output: [‘something1’, ‘something2’, ‘something12’, ‘something17’, ‘something25’, ‘something29’]

Python sort list of strings by length

Answer: Use key attribute in function sort() method:-

Example

Output: [‘A’, ‘BB’, ‘CCC’, ‘FFFF’, ‘DDDD’, ‘EEEEE’]

Q: What is the best way of creating an alphabetically sorted list in Python?

Answer: There are 2 ways:-

  • sort() function – will modify the list it is called on.
  • sorted() function- will create a new list containing a sorted version of the list it is given

Read more and completed examples: – Python sort list (Array) Alphabetically Example | Data Structure

Q: How to sort a list alphabetically in python without sort function?

Answer: Above examples are based on sort function, You can use Sroting algorithm to sort a list alphabetically in python without sort function

Here’s a very short implementation of the Quicksort algorithm in Python, you can use other sorting algorithm for same.

Output: [‘A’, ‘B’, ‘C’, ‘D’, ‘E’]

Do comment if you have questions, doubts or suggestion on this topic.

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.