Python Random Tips #4

This is not a Python Starter Tutorial but advanced Python Tips in a Random Order.

What are the differences between sorted() and sort() :

#1 The output of the sorted() built-in function is a new list and no changes to the original input.

As you can see the original ‘colors’ list is unchanged after the sorted function.

However sort() is a method and it sorts the list “in place” (ie., not giving a new list rather modifies the original input itself).

In the above example, you can see the ‘colors’ list is sorted and the input list got the new sorted values.

#2 sorted() can be used with all objects that are iterable.

The below codes describes usage of sorted() with tuple, list, string and dictionary.

But sort() used against list only (list.sort()).

#3 We can still use the the original input as is after applying sorted(). But we can’t retrieve the original input since list.sort() changes the input itself.

#4 sorted returns a new sorted result but sort returns none. Interesting, isn’t?

sort mutates the list indices, changes (ie., sorts) the list and obviously changes the input itself but returns none as the result. We can use print to see the sorted contents in sort.

We can use ‘print’ to get the list1 contents as below:

Please note the sort is list.sort().

That’s all for now related to sorted() and sort(). See you soon in another post.

Leave a comment

Design a site like this with WordPress.com
Get started