0

I have a dictionary:

{'three': 3, 'two': 2, 'one': 1}

and I need to make some operations with tuple of keys from this dictionary, so I'm trying to use this code:

list(D.keys()) # now I need to sort it
list(D.keys()).sort() # why such construction returns None? (Use print() to track it)

I'm using VS 2013 and IntelliSense prompts me sort method when I print list(D.keys()). So what I'm missing?

p.s Such construction works well:

L = list(D.keys())
L.sort()

Thank You!

1
  • .sort() # why such construction returns None? because read the documentation? Commented Dec 17, 2014 at 18:15

3 Answers 3

1

The .sort() method modifies the list in place and returns None. To use it on a list returned by a method you need to save the list in a variable.

L = list(D.keys())
L.sort()
print L

If you want to eliminate the temporary variable, use sorted:

print sorted(D.keys())
Sign up to request clarification or add additional context in comments.

Comments

1

list.sort() is an in-place sort; you can use sorted to return a new one.

sorted(D)

(It also works on any iterable, so you don’t have to use list(D) [which would be equivalent to list(D.keys())].)

2 Comments

list.sort does not return anything.
I was stating a fact, not a question. Other languages can return self. Python avoided this for good reason see Steve Jessop's answer below.
1

If the question is how to fix your code, John's and minitech's answers both cover it.

If the question is "why does list.sort return None?", then Guido explained his reasoning to the Python-Dev mailing list, sort() return value.

In summary, it is to prevent you writing a series of modifications of an object x as x.sort().compress().spiflicate()

You might not agree with Guido's preferred style, but AFAIK he honestly represented his reasons there, and has said similar things elsewhere. So that's the reason Python is how it is, there's no other motive.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.