I was trying to alphabetically sort my list of strings. I have tried both .sort
and sorted()
but maybe I didn't do it correctly?
Here is my code:
words = input("Words: ")
list1 = []
list1.append(words.split())
print(sorted(list1))
Input: a b d c
Expected output:
['a', 'b', 'c', 'd']
Current output:
[['a', 'b', 'd', 'c']]
Your code is not working because you are trying to sort a list inside a list.
When you call words.split()
it returns a list
. So when you do list1.append(words.split())
it is appending a list into list1
.
You should do this:
words = input("Words: ")
list1 = words.split()
print(sorted(list1))