Stories. Questions. Different perspectives.
Browse WAURE
← Advice & Questions
Technology · Advice & Questions ·

Why is my Python sorted-list variable None after I call names.sort()?

Technology category photographTechnology

My practice script uses `ordered = names.sort()`. Afterwards ordered is None, while names itself has changed into alphabetical order. I expected the method to give me a sorted list to put into the second variable.

Python's sorting guide says list.sort changes the list in place and returns None, whereas sorted builds a new list. Python's sorting guide

Which should I use if I need an alphabetical display and also want to keep the original check-in order? I don't want to hide the None result by reloading data until I understand which operation changed what.

Discussion

5 community replies

The return value is intentional: list.sort sorts names in place and returns None. It hasn't returned a new list for ordered. Your two observations describe the documented operation, not a missing collection of names.

If you need a separate alphabetical list, use sorted on the untouched input list. Python documents that it constructs a new sorted list. Applying it after you've already changed names in place won't reconstruct the earlier check-in sequence.

If changing names itself is what you wanted, call its sort method without assigning the returned value as though it were another list. Choose the operation based on whether the original ordering needs to survive.

Keep a small example that checks both variables: the new display list should be alphabetical, and the input should retain its arrival order. Looking only at ordered no longer being None would miss the second requirement.

That matters for your check-in use: alphabetical order and arrival order answer different questions. Name the two lists by their jobs so the next change doesn't quietly substitute one for the other again.

Join the discussion

More in Technology