Is there a version of list.sort () that returns a sorted list?

I try to perform an inline operation when I need to sort a list as part of a process. The sort function of objects of type list works on the list on which it was called, instead of returning a result.

Python docs confirms the following:

list.sort ()
Sort list items in place.

I tried this through the Python command line and here is the result:

 >>> a = list("hello").sort() >>> print a None >>> b = list("hello") >>> print b ['h', 'e', 'l', 'l', 'o'] >>> b.sort() >>> print b ['e', 'h', 'l', 'l', 'o'] 

Is there a way to skip this problem and make a line like the following possible?

 result = list(random.choice(basesalts)).sort() 

Using the code above will help me reduce the length and verbosity of my code.

+4
source share
3 answers

There is sorted() :

 >>> a = sorted(list('hello')) >>> a ['e', 'h', 'l', 'l', 'o'] 

Also note that you no longer need list() :

 >>> sorted('hello') ['e', 'h', 'l', 'l', 'o'] 

Since basesalts appears as a list of strings, you can simply do:

 result = sorted(random.choice(basesalts)) 

If this is the result you are looking for.

+13
source

Use sorted .

Returns a new sorted list of items in iterable.

 >>> a = sorted(list('hello')) >>> a ['e', 'h', 'l', 'l', 'o'] >>> 

The difference is that the list.sort () method is defined only for lists. In contrast, the sorted () function takes any iterative value.

So you can do

 >>> a = sorted('hello') >>> a ['e', 'h', 'l', 'l', 'o'] >>> 

Take a look at this nice article Sorting Mini-HOW TO .

+5
source

Sorted - your friend is here. It is not a member of a list class function; it is built into a function that takes a list as an argument.

The list of classes does not have a sort function.

 list1 = [ 1, 4, 5, 2] print sorted(list1) >> [1, 2, 4, 5] 
0
source

Source: https://habr.com/ru/post/1398106/


All Articles