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?
>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.