Sorting a List
You need to sort the elements of a list.
Use the sort Python language command:
>>> a = [“it”, “was”, “the”, “best”, “of”, “times”] >>> a.sort() >>> a [‘best’, ‘it’, ‘of’, ‘the’, ‘times’, ‘was’] |
Discussion
When you sort a list, you’ll actually be modifying it rather than returning a sorted copy of the original list. This means that if you also need the original list, you need to use the copy command in the standard library to make a copy of the original list before sorting it:
>>> import copy >>> a = [“it”, “was”, “the”, “best”, “of”, “times”] >>> b = copy.copy(a) >>> b.sort() >>> a [‘it’, ‘was’, ‘the’, ‘best’, ‘of’, ‘times’] >>> b [‘best’, ‘it’, ‘of’, ‘the’, ‘times’, ‘was’] >>> |
See Also
All the recipes between Recipes 6.1 and 6.11 involve the use of lists.