Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort a list of strings alphabetically in Python?

I have a list of strings in Python that I want to sort alphabetically. I’ve tried using the sorted() function, but it doesn’t seem to be working. Here’s an example of what I’ve tried:

my_list = ['banana', 'apple', 'orange']
sorted_list = sorted(my_list)
print(sorted_list)

But the output I get is still the same as the original list:

['banana', 'apple', 'orange']

What am I doing wrong? How can I sort my list of strings alphabetically?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Code1:

  my_list = ['banana', 'apple', 'orange']
  my_list.sort()
  print(my_list)
  my_list = ['banana', 'apple', 'orange']
  my_list.sort()

Code 1 will give you output like [apple, banana, orange]
as .sort() simply sorts by first character of string

Code 2:

 my_list = ['banana', 'apple', 'orange']
 my_list.sort()
 newSortedList=[]
 for i in my_list:
     s="".join(sorted(i))
     newSortedList.append(s)
 print(newSortedList)

Code 2 will give output like [‘aelpp’, ‘aaabnn’, ‘aegnor’]
in code first i have sorted the list using .sort() which changes the my_list to:

[apple, banana, orange]

After which i have individually sorted each string in list with sorted function which returns list of sorted character which will look like:

[‘a’, ‘e’, ‘l’, ‘p’, ‘p’]

then using "".join() i have joined the list and final output is a string:

"aelpp"

which i have appended to newSortedList

The above is done for each string in List.

Hope this was helpful.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading