Sort string by letters python

How to Sort a List Alphabetically in Python

A sorting algorithm puts elements of a list into a particular order. They help reduce the complexity of a problem and can even optimize other algorithms.

Because of its complexity, sorting is one of the most important problems in computer science. In a nutshell, sorting can be defined as arranging items in an ordered sequence. Even though the idea of sorting algorithms looks simple at first, it’s not; research into it started 70 years ago.

Writing a good sorting function on your own is not easy. Luckily, Python comes with built-in sorting functions. This article will explore how to use sort() and sorted() to sort alphabetically in Python.

A Brief Example of Sorting in Python

Sorting algorithms have a wide range of applications. For example, government organizations, commercial enterprises, and financial institutions all organize their data by sorting it. Storing sorted data makes it easier for algorithms to search it later.

So, how exactly can you sort a list in alphabetical order in Python? Let’s look at a quick example.

Note: If you do not know what a list is and why it is a very important Python data structure, check out our article Python Lists, Tuples, and Sets. You might also want to refer to Python Terms Beginners Should Know Part 1 and Part 2 for more information. Finally, I encourage you to enroll in our interactive Python Data Structure course so you can practice these new skills.

Back to Python sorting. Here’s the code for a simple sort:

>>> mylist = ["world", "LearnPython.com", "pineapple", "bicycle"] >>> sorted_list = sorted(mylist) >>> print(sorted_list) ['LearnPython.com', 'bicycle', 'pineapple', 'world']

Above, the list mylist holds the strings “world”, “LearnPython.com”, “pineapple”, and “bicycle” in no particular order. We want to sort this list and store it as a new variable called sorted_list . In Python, sorting a list alphabetically is as easy as passing a list of strings to the sorted() method. Strings are sorted in alphabetical order based on their first letter (A-Z). However, words that start with uppercase letters come before words that start with lowercase letters. (Note: This means “Zebra” will be listed before “apple” because “Zebra” starts with a capital letter.)

Now that we understand what sorting is, we can get started with the code!

Sort a List Alphabetically in Python with sort()

First, let’s sort a list alphabetically in Python with the sort() method. By default, sort() will place the items in ascending (A–Z) order.

Let’s take the same list as before:

>>> mylist = ["world", "LearnPython.com", "pineapple", "bicycle"] >>> mylist.sort() >>> print(mylist) ['LearnPython.com', 'bicycle', 'pineapple', 'world']

However, note that the sort() method will directly modify the initial list of items and that it will not be possible to undo any changes.

Читайте также:  Php form action post get

If you want to sort the items in descending (Z–A) order, you can do it by setting the reverse parameter in sort() as True or False .

>>> mylist = ["world", "LearnPython.com", "pineapple", "bicycle"] >>> mylist.sort(reverse=True) >>> print(mylist) ['world', 'pineapple', 'bicycle', 'LearnPython.com']

And here we go! mylist is now sorted in descending order.

It is important to note that the sort() function sorts in place, i.e. without any additional space requirement. According to Wikipedia:

An in-place algorithm transforms input data without the need for auxiliary structures.

The idea behind an in-place algorithm is space efficiency. In other words, we want to use the minimum of hardware resources to complete the task. Essentially, the output is produced in the same memory space that holds the input; the data is successively transformed in place. This avoids using twice the storage by keeping a copy of the input.

So, should you use sort()?

If you are working with important data and there is even a possibility that you will need to retrieve the original data in the future, then sort() is not the best option because it modifies the original list.

On the other hand, if the data is a copy or unimportant working data, then sort() can be a good option. Another option is to use sorted() instead.

Sort a List Alphabetically in Python with sorted()

Python also has the function sorted() , which we used in the opening example. Contrary to sort() , this method does not modify the original list; it returns a new list with the same content as the original list but in alphabetic order. For example:

>>> new_list = ["Python", "welcome", "hello", "programming", "sorting", "zebra", "alligator"] >>> sort_newlist = sorted(new_list) >>> print(sort_newlist) ['Python', 'alligator', 'hello', 'programming', 'sorting', 'welcome', 'zebra']

Here, the sorted new_list is stored in a variable called sort_newlist . We can always access the new_list variable.

Similar to sort() , sorted() also has a reverse argument that’s False by default. Let’s set it to True to rearrange new_list in descending order:

>>> new_list = ["Python", "welcome", "hello", "programming", "sorting", "zebra", "alligator"] >>> sort_newlist = sorted(new_list, reverse=True) >>> print(sort_newlist) ['zebra', 'welcome', 'sorting', 'programming', 'hello', 'alligator', 'Python']

Sort a List Alphabetically in Python with key

Previously, we saw that sort() and sorted() prioritize uppercase strings. However, we might want case-insensitive sorting. This can be done by setting the key argument to str.lower (which converts all strings to lowercase characters). To use this type of sorting on your data, you will need a function or any other callable that takes one argument and returns a key used for sorting. This technique is fast because the key function is called only once for each input.

>>> mylist = ["world", "LearnPython.com", "pineapple", "bicycle", "Anaconda", "Jupyter"] >>> mylist.sort(key=str.lower) >>> print(mylist) ['Anaconda', 'bicycle', 'Jupyter', 'LearnPython.com', 'pineapple', 'world']

And similarly with sorted() :

>>> mylist = ["world", "LearnPython.com", "pineapple", "bicycle", "Anaconda", "Jupyter"] >>> sort_mylist = sorted(mylist, key=str.lower) >>> print(sort_mylist) ['Anaconda', 'bicycle', 'Jupyter', 'LearnPython.com', 'pineapple', 'world']

We can also use a custom lambda function as the key argument. Let’s say, I have a list of tuples that contain people’s names, occupation, and location. We want to sort them in ascending order based on each tuple’s second item. This can be done with a custom lambda function:

>>> people = [('Anna', 'New York', 'Data Analyst'),('Chris', 'Berlin', 'Software Developer'),('Nancy', 'Toronto', 'Data Scientist')] >>> sorted_people = sorted(people, key=lambda x: x[1]) >>> print(sorted_people) [('Chris', 'Berlin', 'Software Developer'), ('Anna', 'New York', 'Data Analyst'), ('Nancy', 'Toronto', 'Data Scientist')]

The output is a list sorted alphabetically based on the city because x[1] accesses the second item of the tuple (i.e. the city name). You can learn more about how to do lambda sorts in Python in my previous article on custom sort functions.

Читайте также:  Php upload file time

Let’s look at the example above, but this time with sort() :

>>> people = [('Anna', 'New York', 'Data Analyst'),('Chris', 'Berlin', 'Software Developer'),('Nancy', 'Toronto', 'Data Scientist')] >>> people.sort(key=lambda x: x[1]) >>> print(people) [('Chris', 'Berlin', 'Software Developer'), ('Anna', 'New York', 'Data Analyst'), ('Nancy', 'Toronto', 'Data Scientist')]

The result is the same, but we do not have access to the original people list anymore.

The Stability of Python’s Sorting Algorithms

Finally, sort() and sorted() are guaranteed to be stable. Stable sorting means that two objects with identical keys appear in the same order in the sorted output as they do in the original input. In other words, a stable sort ensures that the original order of data with the same rank is retained in the output.

The stability of a sorting algorithm allows the possibility of multiple different correctly-sorted versions of the original list.

Stable sorting algorithms are essential for maintaining the order of equal elements. To be considered as such, they should not change the relative order of elements that are compared. This helps with sorting, for example, if we need to do it in multiple passes (like sorting by city and profession) or something like that.

On the other hand, a non-stable sort could shuffle one element while sorting by another. In this case, sorting by city could shuffle the name order, resulting in a list where the people are sorted by the city but within a city they are not sorted by name, even though they originally were sorted by name.

This is especially important when you’re dealing with more complex lists. For example, you can have a list of tuples with a string as the first element. You can sort the list alphabetically by the first argument, but the original order for the second argument of each tuple is preserved.

Ready to Practice Sorting in Python?

This article explored how to sort a list alphabetically in Python. We discovered how to use sort() and sorted() to sort in Python and how they differ from each other. We also briefly covered the stability of sort algorithms in Python.

Now that you have a solid knowledge about sorting in Python, go ahead and implement your own solutions by playing with the code snippets above.

Finally, do not forget to check our interactive Built-In Algorithms in Python course. It gives you solid, hands-on practice in programming with Python. You can also visit LearnPython.com to learn more about our Python courses.

Источник

Python Program to Sort a String

Sorting has always been quite a popular utility with lots of applications everywhere, where Python language opts. Python in its language offers a sort function to perform this task. But due to fact that not all the containers in Python are mutable, such as string, the sort function doesn’t work as it is in place tries to sort and immutability stops this. Let’s discuss certain ways in which a string can be sorted.

Читайте также:  Ckeditor no html tag

Example:

Enter String: geeksforgeekseeeefggkkors
Result: eeeefggkkors

Python program to sort a string Using join() + sorted()

The combination of the above functions can potentially solve this particular problem. This task is performed in 2 steps in which first step we get the sorted list of characters and then we join the result to get the resultant sorted string.

Example

Python3

The original string : geekforgeeks String after sorting : eeeefggkkors

Python program to sort a string Using Native Method

To sort a given string with user input using the inbuilt python sort method.

Example

Python3

Output:

Enter String: geeksforgeeks
eeeefggkkors

Python program to sort a string Using sorted() + reduce() + lambda

This particular task can also be performed using the combination of the above 3 functions. Here we join the resultant sorted list of characters using the lambda function joined by the reduce function. Works only for Python2

Example

Python

The original string : geekforgeeks String after sorting : eeeefggkkors

Python program to sort a string Using Bubble sort

Algorithm

1. Convert the string into a list of characters.
2. Use the bubble sort algorithm to sort the list.
3. Join the sorted list to form a string.

Python3

Original string: geekforgeeks String after sorting: eeeefggkkors

Time complexity : O(n^2) because we use the bubble sort algorithm which has a time complexity of O(n^2).
Auxiliary Space: O(n) because we create a new list of characters from the original string.

Python program to sort a string Using merge sort method

This approach uses the merge sort algorithm to sort the characters in the string. It first converts the string into a list of characters, and then recursively divides the list in half until the base case of a single element is reached. The two halves are then merged back together in sorted order using the merge() function. The sorted list is then converted back into a string.

Algorithm:

1.Define a function called “merge_sort” that takes a string “s” as input.
2.If the length of the string “s” is less than or equal to 1, return the string “s”.
3.Otherwise, find the middle index of the string “s” and split the string into two halves, left and right.
4.Recursively apply the merge_sort function on the left and right halves.
5.Merge the left and right halves using the merge function.
6.Define another function called “merge” that takes two sorted arrays “left” and “right” as input.
7.Initialize an empty list called “result” and two indices, “i” and “j”, both set to 0.
8.Compare the first elements of the left and right arrays, and append the smaller one to the result array.
9.Increment the index of the array that contributed the smaller element.
10.Continue steps 8-9 until one of the arrays is empty.
11.Append any remaining elements from the non-empty array to the result array.
12.Return the result array.
13.Convert the sorted list to a string and print the result.

Источник

Оцените статью