1. Home
  2. Docs
  3. Phyton
  4. How to (FAQs)
Last updated 749 days ago

How to (FAQs)

Sort() and sorted() what is the difference between them and when would I want to use one versus the other?

The main difference between the list sorting function() and the sorting function() is that the sorting function() modifies the list for which it is called. The sorted() function will create a new list containing the sorted version of the list that is provided to it. The sorted() function will not change the list passed as a parameter. If you want to sort the list, but you still have the original unsorted version, then you should use the sorted() function. If preserving the original order of the list does not matter, then you can call the sort function() in the list.

The second important difference is that the sorted() function will return a list, so you have to assign the returned data to a new variable. The sort() function modifies the list in place and has no return value.

The example below shows the difference in behavior between sort() and sorted(). After passing to sorted(), the list of vegetables remains unchanged. As soon as the sort() function is called for it, the list is updated.

vegetables = ['squash', 'pea', 'carrot', 'potato']

new_list = sorted(vegetables)

# new_list = ['carrot', 'pea', 'potato', 'squash']
print(new_list)

# vegetables = ['squash', 'pea', 'carrot', 'potato']
print(vegetables)

vegetables.sort()

# vegetables = ['carrot', 'pea', 'potato', 'squash']
print(vegetables)
Was this article helpful to you? Yes No

How can we help?

Archives

Categories

Looking for help ? Contact Support

Welcome to the documentation page of SassLand. Based on the RTF

Create support ticket