Search code examples
pythonsortingslice

Why None is printed when a slice of the list is sorted


The following code

   L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   print(L[2:8].sort(reverse=True))

prints None while I expect it to print L = [1, 2, 8, 7, 6, 5, 4, 3, 9, 10]

  1. Why is it so?

  2. If that's not the way to sort part of the list (a slice), what is, given that I need to do it in the same list, not create another one?


Solution

  • L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    L[2:8] = sorted(L[2:8], reverse=True)
    print(L)
    

    output:

    [1, 2, 8, 7, 6, 5, 4, 3, 9, 10]
    

    This should solve the issue

    This works because when L[2:8].sort(reverse=True), it attempts to sort the slice [3, 4, 5, 6, 7, 8] in reverse order. But since sort() changes the original list which here it is not able to and None gets returned instead.

    But sorted() does not effect the original list and needs to assigned manually to the position.