Python Forum
Beginner. Help needed in sorting
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Beginner. Help needed in sorting
#1
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.
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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.
Reply
#4
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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need help with sorting lists as a beginner Realist1c 1 745 Apr-25-2023, 04:32 AM
Last Post: deanhystad
  Sorting a copied list is also sorting the original list ? SN_YAZER 3 3,059 Apr-11-2019, 05:10 PM
Last Post: SN_YAZER

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020