What is the difference between Sorted() and . Sort()?

Asked

Viewed 10,433 times

5

Why the function sorted() is considered more direct than the method .sort() used in lists with tuples?

  • actually it’s not .sort which is considered more direct?

  • According to my teacher, no.

  • 1

    The Sorted function is more direct if you want to create a second list with the values of the first one, but keep the first one with the original values. If the intention is just to sort the list itself, the Sort function is more direct. The @lf-ziron response shows this in the example

  • Thank you very much, your comment made me very clear.

1 answer

4


In Sort you change the list itself, in Sorted you have a value that you can use in a new variable.

a = [2,1,3];
a.sort();
b = a; //a e b possuem o valor [1,2,3]
a = [2,1,3];
b = sorted(a); //a possui o valor [2,1,3] e b possui o valor [1,2,3]

So I don’t think one is more direct than the other, it just depends on how you apply the sort, if you need to keep the value cluttered somewhere, use Sorted, if the old value doesn’t interest you anymore, use . Sort()

  • 2

    I agree that it will depend on the use, but on average there is always that simple and direct is not even?

  • 2

    Well, in this case I think Sort is more used, since it is not necessary to store the previous value generally

Browser other questions tagged

You are not signed in. Login or sign up in order to post.