[Tutor] sorted function

Alan Gauld alan.gauld at yahoo.co.uk
Fri Apr 14 19:56:12 EDT 2017


On 14/04/17 19:29, shubham goyal wrote:

> sorted function is not working when i am trying to sort the list of strings
> but list.sort() is working. can you please help me understand.

sort() sorts the list "in place". That is it sorts itself.
sorted() returns a sorted copy of the list. It does not
alter the original list

> def front_x(words):
>   ls=[]
>   ls1=[]
>   for str in words:
>       if str[0]=='x':
>           ls.append(str)
>       else:
>           ls1.append(str);
>   sorted(ls)
>   sorted(ls1)

So here you should either do this:

ls.sort()
ls1.sort()

or this:

ls = sorted(ls)
ls1 = sorted(ls1)

In this case I'd suggest the first version is better.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list