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.

Recommended Answers

[icode]mylist.sort()[/icode] works, but it sorts the list in place and returns None
[code]

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', …

Jump to Post

All 2 Replies

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.

Thanks, I used sorted to solve the problem.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.