7

I have a list of strings that I want to sort.

By default, letters have a larger value than numbers (or string numbers), which places them last in a sorted list.

>>> 'a' > '1'
True
>>> 'a' > 1
True

I want to be able to place all the strings that begins with a number at the bottom of the list.

Example:

Unsorted list:

['big', 'apple', '42nd street', '25th of May', 'subway']

Python's default sorting:

['25th of May', '42nd street', 'apple', 'big', 'subway']

Requested sorting:

['apple', 'big', 'subway', '25th of May', '42nd street']
Nir
  • 894
  • 3
  • 13
  • 24

1 Answers1

14
>>> a = ['big', 'apple', '42nd street', '25th of May', 'subway']
>>> sorted(a, key=lambda x: (x[0].isdigit(), x))
['apple', 'big', 'subway', '25th of May', '42nd street']

Python's sort functions take an optional key parameter, allowing you to specify a function that gets applied before sorting. Tuples are sorted by their first element, and then their second, and so on.

You can read more about sorting here.

grc
  • 22,885
  • 5
  • 42
  • 63
  • 5
    This does exactly what the OP asked for. It's worth pointing out though that this will not do [natural sorting](http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort) for string numbers, `'2'` will be listed after `'11'`. – Lukas Graf Jul 08 '14 at 06:08
  • +1. In case your list includes integers, wrap `x` in `str()`: `sorted(a, key=lambda x: (str(x)[0].isdigit(), str(x))` – djoll Nov 02 '16 at 23:35
  • Handy tip, if you want ONLY letters at the front (and characters like '(&$#' etc. at the back) you can use `key=lambda x: (not x[0].isalpha(), x))` – danodonovan Jul 05 '23 at 10:01