# Python puzzler: custom list sort

I’m still a python learner, so someone help me out here.

``````things = [
"36767277_0_col-580_permanences"
"36767277_10_col-580_permanences"
"36767277_11_col-580_permanences"
"36767277_12_col-580_permanences"
"36767277_13_col-580_permanences"
"36767277_1_col-580_permanences"
"36767277_2_col-580_permanences"
"36767277_3_col-580_permanences"
"36767277_4_col-580_permanences"
"36767277_5_col-580_permanences"
"36767277_6_col-580_permanences"
"36767277_7_col-580_permanences"
"36767277_8_col-580_permanences"
"36767277_9_col-580_permanences"
]
``````

Given that the `_` character is the delimiter for these strings, I want to sort this list by the 2nd column (the one with `0`, `10`, `11`, etc.) in ascending numerical order.

What is the best way to do this in python?

``````things = [t[1] for t in sorted((int(s.split("_")[1]), s) for s in things)]
``````

To break this down:

``````(int(s.split("_")[1]), s) for s in things
``````

That converts the list into tuples where the first element is the sort key and the second is the original string. That get sorted (first element in the tuples is used as sort key by default).

Then the outer list comprehension simply pulls the strings out of the sorted tuples.

3 Likes

Or using a callback:
`things = sorted(things, key = lambda s: int(s.split("_"))[1])`

3 Likes
`````` things = sorted(somelist, key=lambda x: int(x.split("_")[1]))
``````
2 Likes

`print(str[:8] + " " + str[8:len(str)]);`

Python String Operations