Alphabetical order in python

How to Sort a List Alphabetically in Python

To sort a list alphabetically in Python, you can use either the “sorted()” or the “list.sort()” method.

Method 1: Using the sorted() method

To sort a list alphabetically in Python, the easiest way is to use the “sorted()” method. The sorted() function sorts the given iterable object in a specific order, either ascending or descending.

The sorted(iterable, key=None) method takes an optional key that specifies how to sort.

To disregard capitalization when sorting a list, set the key to str.

Follow the below steps to sort a list alphabetically.

Step 1: Create a list of strings

Use the square brackets [ ] and add the strings separated by a comma to create a list of strings.

data = ['Elle', 'Miles', 'Kratos', 'Joel', 'Peter', 'Nathan']

Step 2: Pass the list of strings to the sorted() function

data = ['Elle', 'Miles', 'Kratos', 'Joel', 'Peter', 'Nathan'] print(sorted(data))
['Elle', 'Joel', 'Kratos', 'Miles', 'Nathan', 'Peter']

And it returns a list of strings in ascending order.

One thing to note here is that we have not mixed a list with upper and lowercase strings.

data = ['Elle', 'miles', 'kratos', 'Joel', 'peter', 'Nathan'] print(sorted(data))
['Elle', 'Joel', 'Nathan', 'kratos', 'miles', 'peter']

You can see that now the sorting is messed up. So let’s resolve this issue.

Step 3: Add a key parameter

As you can see, words that start with an uppercase letter get preference over those beginning with a lowercase letter.

To sort them independently, add the key parameter.

data = ['Elle', 'miles', 'kratos', 'Joel', 'peter', 'Nathan'] print(sorted(data, key=str.lower))
['Elle', 'Joel', 'kratos', 'miles', 'Nathan', 'peter']

Step 4: Pass the reverse = True to the sorted() function

To reverse the order of the list, add the reverse argument and set it to True.

data = ['Elle', 'miles', 'kratos', 'Joel', 'peter', 'Nathan'] print(sorted(data, reverse=True))
['peter', 'miles', 'kratos', 'Nathan', 'Joel', 'Elle']

The list.sort() will sort it alphabetically. You can add reverse=False/True in the brackets to reverse the order of items: list.sort(reverse=False).

Читайте также:  Python читать до пробела

Method 2: Using the list sort() method

The list.sort() is a built-in Python function that sorts the elements of a list in low to high order.

If the list is of numbers, then by default, they will be sorted in increasing order.

Check out the below step-by-step guide to sort lists alphabetically using the list.sort() method.

Step 1: Create a list of strings with mixed cases

As we saw earlier, use the square brackets [] to create a list of strings with mixed cases.

data = ['Elle', 'miles', 'Kratos', 'joel', 'Peter', 'nathan']

You can see that list of strings consists of upper and lower cases.

Step 2: Use the .sort() method

You can call the .sort() method on the list and pass in the optional parameter “key=str.lower” that will tell the .sort() method to sort the list alphabetically, ignoring the case of the words.

data = ['Elle', 'miles', 'Kratos', 'joel', 'Peter', 'nathan'] data.sort(key=str.lower) print(data)
['Elle', 'joel', 'Kratos', 'miles', 'nathan', 'Peter']

You can see that it is sorted alphabetically regardless of the cases of the string.

Step 3: Sort the list in descending order

To sort the list in descending order, pass the optional parameter “reverse=True” to the .sort() method.

data = ['Elle', 'miles', 'Kratos', 'joel', 'Peter', 'nathan'] data.sort(key=str.lower, reverse=True) print(data)
['Peter', 'nathan', 'miles', 'Kratos', 'joel', 'Elle']

You can see the list.sort() function makes it easy to sort a list alphabetically in ascending or descending order in Python.

Sort a List Alphabetically in Python with key

main_list = [('Krunal', 'Rajkot', 'Data Analyst'), ('Ankit', 'Ahmedabad', 'Software Developer'), ('Rushabh', 'Singapore', 'Data Scientist')] sort_mylist = sorted(main_list, key=lambda x: x[1]) print(sort_mylist)
[('Ankit', 'Ahmedabad', 'Software Developer'), ('Krunal', 'Rajkot', 'Data Analyst'), ('Rushabh', 'Singapore', 'Data Scientist')] 

Conclusion

The best and most efficient way to sort a list alphabetically in Python is to use the sorted() function. The sort() and sorted() functions prioritize uppercase strings.

Leave a Comment Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Источник

Sort a List Alphabetically in Python: 4 Easy Ways (with code)

Sort a List Alphabetically in Python: 4 Easy Ways (with code)

Greetings, Python Holics! We know that alphabetizing a list is a common task that every programmer should know in python. In this article, we will learn how to sort a list alphabetically in python with different methods.

How to Sort a List alphabetically in python?

Being able to sort/organize your data in an ordered sequence is a required skill when working on massive datasets. Sorting your data can even assist you to optimise your method and reducing the complexity of your code. It becomes more important when you are working on a government or organization project.

Let’s see a few ways to alphabetize a list in python:

Method 1) Sorted() Function

The sorted() function is a built-in function in python that takes any iterable like a list and returns a new sort list, that will be alphabetically sorted for a list of strings. It can be done for both increasing and decreasing orders. But note that you can’t sort combined lists of numeric and alphabets.

str= ("python", "java", "tutoring", "Favtutor", "Machine Learning", "Studies", "Code", "Students") x = sorted(str, reverse=False) print(x)
['Code', 'Favtutor', 'Machine Learning', 'Students', 'Studies', 'java', 'python', 'tutoring']

To do this in descending order, we will use the Reverse as a hyperparameter for the order by which you want to sort your list, False is ascending and True is descending.

str= ("python", "java", "tutoring", "Favtutor", "Machine Learning", "Studies", "Code", "Students","Zebra","apple") x = sorted(str, reverse=False) print(x)
['Code', 'Favtutor', 'Machine Learning', 'Students', 'Studies', 'Zebra', 'apple', 'java', 'python', 'tutoring']

In the above output, you may be wondering why Zebra is placed before apple in the sorted list. This is because 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.

Читайте также:  Php ссылки в цикле

But what if we want to sort the original list in place, you can use the sort() method instead.

Method 2) sort() function

The sort function alters the initial list in alphabetical order. No arguments are supplied inside this function. So, when using this method on crucial or priceless data, keep in mind that it overwrites your data and prevents you from retrieving the original after the function has been completed.

An advantage of the sort() function is that it is a space-efficient algorithm that uses the least amount of hardware resources to complete the work since it sorts in place, that is, without the need for additional space. Data is incrementally converted on-site. Updating the input prevents the need for double the storage.

str= ["python", "java", "tutoring", "Favtutor", "Machine Learning", "Studies", "Code", "Students","Zebra","apple"] str.sort() print(str)
['Code', 'Favtutor', 'Machine Learning', 'Students', 'Studies', 'Zebra', 'apple', 'java', 'python', 'tutoring']

These two methods are also great for sorting tuples in python. It can also improve the efficiency of searching for elements in tuples.

Method 3) Using a key

As we have already seen, the two functions sorted() and sort() give uppercase strings precedence over lowercase ones. We could want to sort without regard to the case.

Setting the key argument to str.lower will accomplish this. You will require a function or other callable that accepts one argument and returns a sorting key in order to utilize this style of sorting on your data. This is because the key function is only called once for each input, this strategy is quick.

s= ["python", "java", "tutoring", "Favtutor", "Machine Learning", "Studies", "Code", "Students","Zebra","apple"] lower_string=[i.lower() for i in s] s.sort() print("using sort function","\n",s) print("---------------------------------------------------------") x = sorted(s, reverse=False) print("using sorted function","\n",x)
using sort function ['Code', 'Favtutor', 'Machine Learning', 'Students', 'Studies', 'Zebra', 'apple', 'java', 'python', 'tutoring'] --------------------------------------------------------- using sorted function ['Code', 'Favtutor', 'Machine Learning', 'Students', 'Studies', 'Zebra', 'apple', 'java', 'python', 'tutoring']

Method 4) Without using any function

There are some situations where you need to know some simple alternative ways without using a built-in method. Let’s see how to sort a list alphabetically in Python without the sort function.

Читайте также:  Pie charts in java

We can use any popular sorting techniques like quick sort, bubble sort, or insertion sort to do it. Let’s learn how to do it with Quick sort, which can be two to three times faster. The algorithm’s foundation is Pivot values, which are frequently implemented recursively. When a pivot is present, everything to the left of the pivot is always smaller, and everything to the right is always larger.

def sort(lst): if not lst: return [] return (sort([x for x in lst[1:] if x  lst[0]]) + [lst[0]] + sort([x for x in lst[1:] if x >= lst[0]])) s= ["python", "java", "tutoring", "Favtutor", "Machine Learning", "Studies", "Code", "Students","Zebra","apple"] print(sort(s))
['Code', 'Favtutor', 'Machine Learning', 'Students', 'Studies', 'Zebra', 'apple', 'java', 'python', 'tutoring']

Conclusion

Today we discussed sorting a list in alphabetical order using various methods in python with code. But remember that a stable sorting algorithm must maintain the comparative elements’ original relative order in order to be taken into account. Happy Learning 🙂

Источник

How to Sort String in Alphabetical Order Using Python

In this tutorial, learn how to sort string in alphabetical order in Python. The short answer is to use the string as the argument of the sorted() and place them inside the join() .

You can also use the reduce() and the accumulate() functions of Python for sorting a string in Python. Let’s find out with the different examples given below.

Method 1: Using join() with sorted() to Sort String Alphbatically in Python

To sort the string in alphabetical order, you have to use the sorted() function and pass the string variable as its argument. After that, place them inside the join() function as the argument of it. See the example below to learn the method.

The above example shows the use of the function that arranges the string character in proper sequence alphabetically. It sorts the strings alphabetically in ascending order (a to z & A to Z).

Method 2: Using reduce() with sorted() to Sort String in Alphabetical Order in Python

When you want to sort the string alphabetically, you can use the reduce() function. Inside that function, you have to use the sorted() with the string variable as its argument.

The above example contains the same output that you have got in the first example above.

Method 3: Using accumulate() and sorted() in Python

In addition to the above methods, you can also use the accumulate() function that takes the sorted() as its argument. Also, pass the string variable as the argument of the sorted() function in Python.

After that, you have to use the tuple() function to convert the result into a string in Python. You can check the below example to get the use of the method.

Источник

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