0

How do I sort a list in Python alphabetically? The code that is used for Python 2 doesn't seem to work:

mylist.sort()

Since the file I'm working with has all text in the same case, case doesn't matter here. Please help.
Thanks.

2
Contributors
2
Replies
6
Views
6 Years
Discussion Span
Last Post by king_koder
1

mylist.sort() works, but it sorts the list in place and returns None

>>> L = "the file I'm working with has all text in the same case, case doesn't matter here".split()
>>> print(L)
['the', 'file', "I'm", 'working', 'with', 'has', 'all', 'text', 'in', 'the', 'same', 'case,', 'case', "doesn't", 'matter', 'here']
>>> L.sort()
>>> print(L)
["I'm", 'all', 'case', 'case,', "doesn't", 'file', 'has', 'here', 'in', 'matter', 'same', 'text', 'the', 'the', 'with', 'working']
>>> print(L.sort())
None

Otherwise, you can use newlist = sorted(mylist) which doesn't change the original list, but returns a new list.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.