How To Sort List Of Strings In Alphabetically
Last Updated :
19 Jan, 2024
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, the strings that start with uppercase characters(A-Z) come before strings that begin with lowercase characters(a-z). This means the string "Apple" will come before the string "apple" in alphabetical order, as "Apple" starts with an uppercase character.
Sort the List Of Strings Alphabetically
Below, are the various ways to alphabetically sort a list of strings in Python.
- Naive Approach
- Using Sort() Function
- Using sorted() function
Naive Approach
In this example, code defines a function naive_sort
to sort a list of strings alphabetically using a nested loop and swapping elements if they are out of order. It then creates a list of strings str_list
, applies the sorting function.
Python3
def naive_sort(strings_list):
n = len(strings_list)
# Iterate over each element in the list
for i in range(n):
# Compare each element with the remaining elements
for j in range(i + 1, n):
# If the current element is greater than the next one, swap them
if strings_list[i] > strings_list[j]:
strings_list[i], strings_list[j] = strings_list[j], strings_list[i]
str_list = ["hello", "world", "learn", "geeksforgeeks", "courses", "python"]
naive_sort(str_list)
print("Sorted List:", str_list)
Output :
Sorted List: ['courses', 'geeksforgeeks', 'hello', 'learn', 'python', 'world']
Using sort() function
The sort() function sorts the elements of a list in ascending order by default. The sort() function sorts the list in place, meaning it will modify the original list.
Syntax : <list_object>.sort(reverse)
Sort in Alphabetically Order : Below, given code initializes a list of strings (str_list
), sorts it alphabetically using the sort()
method, and then prints the sorted list.
Python3
str_list = ["hello", "world", "learn", "geeksforgeeks", "courses", "python"]
print("Original list:", str_list)
# Sort the list
str_list.sort()
print("Sorted list:", str_list)
Output :
Original list: ['hello', 'world', 'learn', 'geeksforgeeks', 'courses', 'python']
Sorted list: ['courses', 'geeksforgeeks', 'hello', 'learn', 'python', 'world']
Using sorted() function
The sorted() function sorts the elements of a list passed to it in ascending order by default. The sorted() function sorts returns a new sorted list, which means it will leave the original list unchanged.
Syntax : sorted(<list_object>, reverse)
Sort in Alphabetically Order : Below code first prints the original list and then prints the sorted version of the list using the sorted()
function, demonstrating the strings arranged in ascending alphabetical order.
Python3
str_list = ["JavaScript", "Java", "ReactJS", "Flask", "Flutter"]
print("Original List:", str_list)
sorted_str_list = sorted(str_list)
print("Sorted List:", sorted_str_list)
Output :
Original List: ['JavaScript', 'Java', 'ReactJS', 'Flask', 'Flutter']
Sorted List: ['Flask', 'Flutter', 'Java', 'JavaScript', 'ReactJS']
Use `sort()` or `sorted()` Based on Your Needs.
- Use
sorted()
when:- Dealing with critical data that should not be altered.
- Needing the original data for future reference.
- Avoiding modifications to the original list.
- Willing to trade off additional memory space for a new sorted list.
- Use
sort()
when:- No future use of the original list is required.
- Prioritizing in-place sorting to save memory.
- Open to modifying the original list directly.
Both methods have their uses, and you can even use sorted()
when the original list won't be used again. It ultimately depends on your specific needs and considerations.
Related Article:
- sort() in Python
- sorted() in Python
Conclusion
In this article, we looked at two different ways of sorting a list of strings alphabetically in Python using the sort() and sorted() function with the help of examples. We also looked at using reverse=True as a parameter to sort the list of strings in reverse order. We also looked at which one is better to use when as both sort() and sorted() functions can help sort the list of strings alphabetically.
Similar Reads
How to Sort a String Characters Alphabetically in Ruby?
This article focuses on discussing how to sort a string's characters alphabetically in Ruby. Using Chars and SortSyntax: sorted_string = string.chars.sort.join Example: In this example, the string is converted into an array of characters, and the sort method is used to sort the array. Ruby # Origina
2 min read
Python | Sort the list alphabetically in a dictionary
In Python Dictionary is quite a useful data structure, which is usually used to hash a particular key with value, so that they can be retrieved efficiently. Let's see how to sort the list alphabetically in a dictionary. Sort a List Alphabetically in PythonIn Python, Sorting a List Alphabetically is
3 min read
How to Sort an Array alphabetically in Ruby?
Sorting an array alphabetically is a common operation in Ruby and can be done using different methods. Sorting an array alphabetically refers to arranging its elements in the order of their lexemes either increased or decreased depending on such order. We will consider some methods that can help us
2 min read
How to returns a passed string with letters in alphabetical order in JavaScript ?
Let's say we need to convert the string into alphabetical order. For example: geeksforgeeks -> eeeefggkkorss Approach: The task is to create a function that takes a string and returns the alphabetical order of that string. Hence to achieve this we will go under the split, sort, and join method in
2 min read
How to alphabetize in Excel: sort columns and rows
How to Alphabetize in Excel - Quick StepsOpen MS ExcelSelect Data Go to the Data Tab >> Click on "Sort & Filter"Select "A to Z" In Excel, alphabetizing your data can make finding information much easier. Whether you're organizing names, dates, or any other information, sorting columns and
9 min read
Python code to print common characters of two Strings in alphabetical order
Given two strings, print all the common characters in lexicographical order. If there are no common letters, print -1. All letters are lower case. Examples: Input : string1 : geeks string2 : forgeeks Output : eegks Explanation: The letters that are common between the two strings are e(2 times), g(1
2 min read
How to Sort a list in Scala?
Sorting a list is a common operation in programming, and Scala provides convenient ways to accomplish this task. In this article, we'll explore different methods to sort a list in Scala, along with examples. Table of Content Using the sorted Method:Using the sortBy Method:Using the sortWith Method:S
2 min read
How to Alphabetize a Dictionary in Python
Alphabetizing a dictionary in Python can be useful for various applications, such as data organization and reporting. In this article, we will explore different methods to alphabetize a dictionary by its keys or values.Dictionary OrderingIn Python, dictionaries are a powerful data structure that all
2 min read
Capitalize Each String in a List of Strings in Python
In Python, manipulating strings is a common task, and capitalizing each string in a list is a straightforward yet essential operation. This article explores some simple and commonly used methods to achieve this goal. Each method has its advantages and use cases, providing flexibility for different s
3 min read
Convert string to a list in Python
Our task is to Convert string to a list in Python. Whether we need to break a string into characters or words, there are multiple efficient methods to achieve this. In this article, we'll explore these conversion techniques with simple examples. The most common way to convert a string into a list is
2 min read