7 Comments
Dec 20, 2023Liked by Stephen Gruppetta

Hi, I really liked your article. Never realised that keys can be supplied in so many places!

Please note that instead of sorting twice to get a list of names sorted on nr of 'a's and names with equal nr of 'a's alphabetically , you could sort just once:

sort_names.sort(key=lambda x: (x.lower().count('a'), x))

Expand full comment
author

Thanks Paul. Glad you enjoyed it.

And yes, you make a great point about returning a tuple in the `lambda`. This would require a discussion about ordering in tuples, too, but it would avoid one of the `.sort()` calls!

Expand full comment

This was probably the most confusing thing in Python when I started, and the docstring of sorted never helped :)

Expand full comment
author

It does feel like magic! I actually went to check what the docstring says. It’s just this: “A custom key function can be supplied to customize the sort order”. Not that helpful unless you already know what key does!

Expand full comment

Yes, that's cryptic for a beginner. They should do better.

Expand full comment
Dec 7, 2023Liked by Stephen Gruppetta

I'm a little confused about the unpacking operator. Not how to use it, because you made that fairly clear, but that it is necessary. All this time, I've been printing lists directly. It appears to ignore the sep argument, but Python will print a list or any other iterable directly

Expand full comment
author

That's a great point. Yes, you can print the list directly but this will print it out in the form of a Python list, with the square brackets and quotation marks and commas and all that. If you're fine with that, that's great, but sometimes you want to display the items in some other form, without all the clutter of the list syntax (especially if it's an output for a non-Python audience). Unpacking allows you to do so…

And as you say, the `sep` parameter won't work if you print the list directly since you only have one object as argument for `print()` in this case, so there's nothing to separate

Expand full comment