Write a python program to sort words in alphabetical order
In this exercise, you will learn how to sort words in alphabetic order using Python. Python is a high-level, open source, general-purpose programming language. It enables us to write clear, logical applications for small and large tasks. It has a set of useful libraries, packages, and functions that minimise the use of code in our day-to-day life. A simple Python programming task is sorting a list of words or items in alphabetical order. You may need to add this feature to sort a list of items in e-commerce application development.
Python sort words in a list in alphabetical order
Python provides a predefined function sorted() that returns a sorted list of the specified list. It accepts both object types, numbers and strings. Numbers are sorted numerically, and strings are sorted alphabetically. But, we can not provide a list containing both.
sorted(iterable, key, reverse)Here, the iterable is the required parameter that contains either sort, list, dictionary, or tuple. The key is the optional parameter, which is a function to decide the order parameter. The reverse is also optional, which accepts a boolean value. False will sort ascending, True will sort descending.
Python Alphabetic Order Example
In the given example, we have sorted words in ascending order-
Output of the above code -
(env) c:\python37\Scripts\projects>test.py ['bike', 'car', 'motorcycle', 'train', 'truck']Here is the other alphabetic order example in descending order-
Output of the above code -
(env) c:\python37\Scripts\projects>test.py ['truck', 'train', 'motorcycle', 'car', 'bike']Python Sort Words in a String in Alphabetical Order
In the given example, we have written a program to take a string input from the user and sort the words in that given string in alphabetical order.
Output of the above code0-
need an explanation for this answer? contact us directly to get an explanation for this answerEnter a string: John is smaller than Smith The sorted words are: John Smith is smaller than