Sorting lists alphabetically is a common task in Python, whether we're organizing names, cleaning data or building an interface. Python makes sorting easy with several built-in methods and libraries for both simple and advanced sorting needs.
Let's look at some of the most common methods one by one:
Using sort() Method
The simplest way to sort a list alphabetically is by using sort() method. This method modifies the original list in place, arranging its elements in ascending order. sort() method is the most efficient in terms of both time and space since it sorts in place with minimal memory usage.
a = ["Prajjwal", "Kareena", "Brijkant", "Aryan"]
a.sort()
print(a)
Output
['Aryan', 'Brijkant', 'Kareena', 'Prajjwal']
Explanation: sort() method arranges the list elements in alphabetical order.
Note: Use sort() when you don’t need to retain the original list and want an efficient, in-place sorting solution.
Using sorted() Function
If you need to keep the original list unchanged and create a new sorted list, sorted() function is a better choice. It returns a new list with the sorted elements.
a = ["Prajjwal", "Kareena", "Brijkant", "Aryan"]
b = sorted(a)
print(b)
Output
['Aryan', 'Brijkant', 'Kareena', 'Prajjwal']
Using numpy.sort() for Large Datasets
The numpy library provides a highly optimized sorting function, particularly useful for large datasets.
import numpy as np
a = ["Prajjwal", "Kareena", "Brijkant", "Aryan"]
b = np.sort(a)
print(b)
Output
['Aryan' 'Brijkant' 'Kareena' 'Prajjwal']
Sorting a List of Strings with Different Cases and Lengths
By default, Python's sorting is case-sensitive. To sort alphabetically while ignoring case, use key=str.lower parameter. You can sort a list based on the length of its elements using len function as the key.
a = ["Prajjwal", "Kareena", "Brijkant", "Aryan"]
b = sorted(a, key=str.lower)
print(b)
b.sort(key=len)
print(b)
Output
['Aryan', 'Brijkant', 'Kareena', 'Prajjwal'] ['Aryan', 'Kareena', 'Brijkant', 'Prajjwal']
Explanation:
- sorted(a, key=str.lower) sorts the list lexicographically.
- sort(key=len) sorts the list based on the length of each element in the list.
Using itertools.islice for Sorting in Chunks
For more complex sorting tasks, you can split a list into chunks and sort each chunk individually.
from itertools import islice
a = ["Prajjwal", "Kareena", "Brijkant", "Aryan"]
# Split and sort in chunks of 2
it = iter(a)
b = [sorted(list(islice(it, 2))) for _ in range(0, len(a), 2)]
print(b)
Output
[['Kareena', 'Prajjwal'], ['Aryan', 'Brijkant']]
Explanation:
- it = iter(a) creates an iterator over the list.
- islice(it, 2) takes 2 elements at a time from the iterator.
- sorted(list(...)) sorts each chunk alphabetically (i.e., in lexicographical order).
Also read: Python, sort(), sorted(), np.sort(), iter(), islice().