Explain Codes LogoExplain Codes Logo

Why does "return list.sort()" return None, not the list?

python
list-sort
method-chaining
timsort
Anton ShumikhinbyAnton Shumikhin·Aug 11, 2024
TLDR

To get a sorted list, use sorted() immediately before returning:

return sorted(my_list)

And with list.sort(), which modifies my_list in-place, follow it with a separate return statement:

my_list.sort() # Jedi mind trick: "You don't need to 'return' me" return my_list # "Phew! Saved by the bell!

Behind the scenes with sort() and sorted()

Differentiating the twins: in-place sort vs. generating a new list

Here's the secret: sort() is the more modest twin. It quietly works its magic and transforms the list in-place, changing the order of elements without creating a new list. On the flip side, the show-off twin sorted() generates an entirely new sorted list, leaving the original one untouched.

Chain of disappointments: the pitfalls of method chaining

Method chaining, calling another method directly on the output of a previous method, is rarely boring. However, pythons have swallowed the advice of their creator, Guido van Rossum, about avoiding method chaining when it doesn't produce new values. With list.sort(), you're waiting for something that's not coming (None), setting yourself up for a single-line tragedy.

Time travelers take note: preserving the original list order

In scenarios where the timeline of Doctor Who is less complicated than your data structure, preserving the original list order can be crucial. That's when sorted() comes to the rescue, allowing you to travel back in space-time to your unaltered original list whenever you need.

How to avoid falling into the sort() rabbit hole

The assignment of despair: why answer = my_list.sort() is a dead end

Walking into the answer = my_list.sort() trap is like expecting a pizza but getting broccoli. It won't end well. This practice will assign None to answer because .sort() doesn't return the sorted list. Beware of the broccoli!

The None conundrum

Some believe that all methods should bring them a None as a souvenir. But hold your horses! Many Python methods change their objects and return None as a silent acknowledgement of their covert operations. Understanding this enigmatic nature is the first step toward becoming a Python whisperer.

Diving deeper into Python's list.sort()

list.sort(): the guy behind the curtain

Meet the sorcerer behind list.sort(): Timsort. Timsort is an adaptive sorting algorithm optimized for different data elements. This slice 'n' dice method laundry-sort your stuff sneakily in the background!

Sprucing up your sort with key functions and reverse ordering:

my_list.sort(key=len, reverse=True) # "Hey Python, 'sort()' this for me by length, but in reverse. I like to live dangerously."

And voila! Your wish is Python's command! The list is sorted based on the length of its items, but in code-thug life reverse order. Yeah, Python got your back!

Picture this: You order a pizza, and request the chef to slice it up:

Before: 🍕 (whole pizza) After: [🍕🍕🍕🍕🍕🍕🍕🍕] (sliced pizza)

You then tell the chef to sort the slices:

pizza_slices.sort() # Chef: "Alright, boss wants pizza sorted. Eeny, meeny, miny, moe..."

But when you ask him to return the sorting process:

return pizza_slices.sort() # Chef: "Wait, how am I supposed to 'return' the sorting process?"

You get nada, zilch, zero!

You expect: [🍕🍕🍕...] (sorted slices) But get: 🤷‍♂️ ("Expected pizza. Got existential crisis instead.")

Remember, .sort() is a diligent worker, but doesn't like to show off. It works behind-the-scenes, sorting your list in-place, and bows out quietly with a None.

The Great Debate: To use sort() or to use sorted()

The need for speed: decisions based on performance

If you're someone who enjoys high-speed car chases, the sort() method might be your speed demon. It's more efficient than sorted(), as it doesn't waste resources creating a new list. But, life's not all about speed. Consider using sorted() if you value memory efficiency over clock cycles.

Academia vs Reality: functional vs practical programming style

While sorted() aligns nicely with the functional programming style, ideal for creating expressive one-liners and attracting LinkedIn recruiters, sort() lets you get down to brass tacks and modify data in-place without the fluff.

Clarity and intent: If code could talk

In Python, readability isn't just sexy, it's downright enticing! Choosing between sort() and sorted() can make your intentions crystal clear. If your list needs a makeover as part of a larger plan, sort() subtly suggests that the original order isn't important. On the other hand, sorted() signals that you're just trying the sorted look for size and the original list remains unchanged.