FAQ: Working with Lists in Python - Sorting Lists II


#1

This community-built FAQ covers the “Sorting Lists II” exercise from the lesson “Working with Lists in Python”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science
Data Science

FAQs on the exercise Sorting Lists II

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!


#2

Hi all,

So I am curious about why we would want to use either .sort() or sorted()over the other.

Is there a “more standard” option?

It seems like unless you are trying to play code golf, .sort() can do everything and more that sorted() can.


#3

The biggest difference between the two is that one is a list method, list.sort() and the other is a global function. Only list objects have a sort attribute.

Another difference is that list.sort is insitu which means it does not create a copy, but sorts the list in place. It does not return anything (except None). This is not a method to use on an object passed to a function if we wish to preserve the original order.

sorted() on the other hand does create a copy and sorts that, then hands it off to the assignment variable. The original list is unaffected.

Because sorted is a global function, it can take any iterable and return a sorted list from that…

>>> sorted((3,7,4,9,2,1,7))
[1, 2, 3, 4, 7, 7, 9]
>>> sorted({'one':1, 'two':2,'three':3,'four':4,'five':5})
['five', 'four', 'one', 'three', 'two']
>>> sorted([3,7,4,9,2,1,7])
[1, 2, 3, 4, 7, 7, 9]
>>> sorted('this is a string')
[' ', ' ', ' ', 'a', 'g', 'h', 'i', 'i', 'i', 'n', 'r', 's', 's', 's', 't', 't']
>>> 

If we peer a little further down the rabbit hole we can learn a few more things about both the method and the function, in particular the optional arguments such as key and reverse but I’ll leave that for you to dig into.

Not really, since it depends upon the author’s aims and objectives. We make the choice depending on how we want things the be in the end.

If, for instance we are writing a median function that takes a sample which has a chronological order (last on is most recent) that we wish to preserve. We would not .sort() this in our function since that order would be lost. Instead,

s = sorted(sample)

where s is a sorted copy of sample but sample is unchanged.


#4

Awesome, concise answer.

Thanks!