Sorting strings by length - functional Python I'm trying to port this little F# snippet while staying pythonic:

["something"; "something else"; "blah"; "a string"] |&gt; List.map (fun p -&gt; p, p.Length) |&gt; List.sortBy snd


In case you don't speak F#, it gets the length of each string, then sorts by length.

Output:


[("blah", 4); ("a string", 8); ("something", 9); ("something else", 14)]



In Python, this is the best I could do so far:

sorted([(p, len(p)) for p in ["something", "something else", "blah", "a string"]], key=lambda a:a[1])


While correct, this doesn't look very elegant to me, or maybe it's just my non-pythonic eye.

Is this pythonic code? How would you write it? Maybe an imperative style is more appropriate?
data = ["something", "something else", "blah", "a string"]
result = [(x, len(x)) for x in sorted(data, key = len)]


Basically, its more straightforward to sort first then decorate. Although, I'm not sure why you would need the length of the list in your tuple. If you don't really need it sorting by length can be much shorter.

EDIT:

If all I wanted was to output the data, I'd do it like this:

for string in sorted(data, key = len):
    print string, len(string)


If you really wanted to eliminate the two references to len you could do:

mykey = len
for string in sorted(data, key = mykey):
    print string, mykey(string)


But unless you are reusing the code with different mykey's that doesn't seem worthwhile.