How to sort a list of strings in Python?

PythonServer Side ProgrammingProgramming

To sort a list in place, i.e., sort the list itself and change ordering in that list itself, you can use sort() on the list of strings. For example,

>>> a = ["Hello", "My", "Followers"]
>>> a.sort()
>>> print a
['Followers', 'Hello', 'My']

If you want to keep the original list intact and instead want a new list of the sorted elements, you can use sorted(list). For Example,

>>> a = ["Hello", "My", "Followers"]
>>> b = sorted(a)
>>> print b
['Followers', 'Hello', 'My']

       

raja
Published on 13-Dec-2017 18:07:19
Advertisements