Reputation: 21
I am trying to sort all the words of a text file in alphabetical order. Here is my code:
filename=input('Write the name of the file :')
fh=open(filename)
wlist=list()
for line in fh:
line=line.rstrip()
ls=line.split()
for w in ls:
if w not in wlist:
wlist.append(w)
print(wlist)
The output is ok but whenever I try print(wlist.sort())
it gives 'None' as output instead of sorting the wlist.what is the problem in my code?
Thanks in advance.
Upvotes: 1
Views: 48
Reputation: 286
There were some indentation inconsistencies but other then that its good. As a general rule the function sort()
only performs the ordering of items in the list. If you want to return the list print it:
filename=input('Write the name of the file :')
wlist = []
# I would recommend opening files in this format
with open(filename) as f_obj:
read = f_obj.readlines()
for line in read:
ls = line.split(' ')
for w in ls:
if w not in wlist:
wlist.append(w)
wlist.sort()
print(wlist)
Upvotes: 2
Reputation: 47790
list.sort
sorts the list in-place and returns None
.
If you want to print the sorted list, do it afterwards:
wlist.sort()
print(wlist)
Separately, instead of checking the list for duplicates every time it'd be far more efficient to make a set
of the words, and then sort that with sorted()
:
words = set()
for line in file:
for word in line.split():
words.add(word)
print(sorted(words))
Upvotes: 6