Python Forum

Full Version: Beginner. Help needed in sorting
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I'm new to this forum. I need help in below code.

>>> import keyword
>>> print(keyword.kwlist)
Output:
Output:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
I try to sort the output in alphabetical order using the below code
import keyword
a = keyword.kwlist
print(a.sort())
I'm getting output as None. Could anyone help me sorting out this problem. Thanks in advance. Looking forward.
list.sort() method works in-place and returns None

import keyword
my_list = keyword.kwlist
my_list.sort()
print(my_list)
or

import keyword
my_list = keyword.kwlist

print(sorted(my_list))
print(my_list) # note that list is not sorted in-place
Hi Buran,

Much appreciate for your quick reply. Thank you. But still the output remains same. Not sorted yet. Please check and help again. Looking forward for your reply.
Actually it is sorted right from the start (i.e. you would not see difference anyway). The sort order is A..Za..z, i.e. Z is before a
I would suggest that you experiment with your own list.

You can use key argument of sort method if you want to pass custom sort function.
Hi Buran,

Yes, you are right. It's already sorted. I've not noticed. Great help. Much appreciated. Thank you Buran. Have a good day. Smile