Why when ordering a list with Sort(), returns None?

Asked

Viewed 98 times

3

The following script sorts a dictionary:

d = {'a': 10, 'g': 15, 'c': 67, 'z': 90, 'e': 144}

ordenada = list(d.keys()) # gera uma lista das chaves do dicionário (protegida por uma tupla)
ordenada.sort() # ordena a lista de chaves
for chave in ordenada:
    print(chave, '=', d[chave], end=', ') # mapeia os valores com as chaves ordenadas

I tried this way too and I couldn’t:

ordenada = list(d.keys()).sort()
print(ordenada) # está retornando None

I wanted to understand why by applying the method sort() on the same line it is returning None. I thought the object orientation paradigm would be applied here, where I first transform d.keys() in an object list to then put it in order. Does it make sense? Taking advantage, if you can, to explain the meaning of None in some other more elaborate case.

1 answer

4


According to the documentation, list.sort changes the list in-place (that is, the list elements are rearranged internally, rather than returning another list). There it is also said that "it does not Return the Sorted Sequence" (does not return the ordered list).

What is more, the documentation also states that:

The methods that add, subtract, or rearrange their Members in place, and don’t Return a specific item, Never Return the Collection instance itself but None.

That is, methods such as sort, that change the content in place and do not return to their own list, return None.


If you want another list returned, use sorted:

d = {'a': 10, 'g': 15, 'c': 67, 'z': 90, 'e': 144}
ordenada = sorted(d.keys())
for chave in ordenada:
    print(chave, '=', d[chave], end=', ')

Obs: the for above prints an extra comma at the end, so a way to print correctly would be:

print(', '.join(f'{chave} = {d[chave]}' for chave in ordenada))

Printing:

a = 10, c = 67, e = 144, g = 15, z = 90

Browser other questions tagged

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