Hey everyone,

I tried a site search but it turned up cold. Has anyone here ever written a small method to take a list of names and sort them in alphabetical order? If so, would you mind posting it up, or directing me to a tutorial that would explain this better?

if you have a list its as simple as calling the sort() method

li  = ['a','h','w','j','s','r','y']
li.sort()
print li

Wow, thought I tried that.

Sorry.

If you want a copy of the sorted object, instead of directly modifying the object itself, use the built-in "sorted" function.

>>> L = ['z', 'aa', 'g', 'ab', 'yz']
>>> Ls = sorted(L)
>>> Ls  # returned copy
['aa', 'ab', 'g', 'yz', 'z']
>>> L  # original stays the same
['z', 'aa', 'g', 'ab', 'yz']

And if you use it on strings, it breaks them apart into a list of characters, and then proceeds to sort that. And it works on tuples (but returns the sorted one as a list!):

>>> sorted("Hello World!")
[' ', '!', 'H', 'W', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r']
>>> sorted((5,3,4,1,2))
[1, 2, 3, 4, 5]

Just in case you wanted to sort something without modifying the original, or sort a string!

Wow, thought I tried that.

Sorry.

Hahaha! Never apologise for a question, a stupid question is one that doesnt get asked :)

This question has already been answered. Start a new discussion instead.