Method "Sort" returning only "None", what is the reason?

Asked

Viewed 723 times

3

I’m solving a problem in Python 3, about lists.

Part of my solution involves sorting a list of values float, I decided to use the method sort. This method should return the already ordered list in ascending order, but that is not what is happening.

The function I’m writing works more or less like this:

def inverter(lista):
    lista_invertida = []

    lista = lista.sort()
    lista_invertida = lista[::-1]

    return lista_invertida


However this was not working, I did a test to check if there was something "broken".

I wrote a print to show me the list before and after it is ordered.

Before being ordered the list was like this:

34.7, 43.5, 31.1, 40.7, 20.3, 19.9

Soon after the ordering the list was like this:

None, None, None, None, None, None

This broke the function I had written, the interpreter kept trying to invert the list only formed by None... I would like to know if there is something wrong, and/or if there is a way to correct that return.

2 answers

5


The method list.sort modifies the own llista, does not return a new object as it occurs with the function sorted. This way, you are overwriting the object lista with the return of list.sort, that is None.

To correct, rather than do:

lista = lista.sort()

Just do

lista.sort()

However, if the idea is to reverse the list later, why not already reverse order?

lista.sort(reverse=True)

Then you won’t have to lista[::-1] to invert the list.

BUT BE VERY CAREFUL

Once using list.sort within the function, your list out of function will also be changed. If you want the list to remain unchanged when calling the function the ideal is to use the function sorted, which creates a new list to sort:

def inverter(lista):
    return sorted(lista, reverse=True)

For example:

Using sorting with list.sort

>>> lista = [4, 5, 2, 6]
>>> print(inverter(lista))
[6, 5, 4, 2]
>>> print(lista)
[6, 5, 4, 2]

Realize that lista was also amended.

Using sorting with sorted

>>> lista = [4, 5, 2, 6]
>>> print(inverter(lista))
[6, 5, 4, 2]
>>> print(lista)
[4, 5, 2, 6]

Realize that lista was not changed after calling the function.

  • Perfect!!! The sort(reverse = True) solved, by still having some things I need to treat.

3

instead of using list = list.Sort() use list only.Sort()

  • It works, but @Anderson Carlos Woss' response was more complete and still avoided a possible error by changing the list globally.

Browser other questions tagged

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