Out of sorts

The sorted() function returns a new sorted list while leaving the source list unchanged. It works with both lists and immutable sequence objects. This function is new in Python 2.4.

>>> mylist = [1, 10, 2, 9, 3, 8, 4, 7, 5, 6] >>> mynewlist = sorted(mylist) >>> mynewlist

>>> mylist # original list is unchanged

TECHNICAL In contrast, the list method sort() changes the original list in place. STUFF

To use the sorted() function in a for statement, type the following (substituting the name of your sequence object):

>>> mytuple = ("an", "african", "or", "european", "swallow", "?") >>> for f in sorted(mytuple): ... print f,

? african an european or swallow

Was this article helpful?

0 0

Post a comment