Question 6.9: Sorting a List You need to sort the elements of a list....

Sorting a List

You need to sort the elements of a list.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

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.

Related Answered Questions

Question: 6.15

Verified Answer:

Use the for command to iterate over the keys of th...
Question: 6.14

Verified Answer:

Use the pop command, specifying the key for the it...
Question: 6.11

Verified Answer:

Use the Python language feature called comprehensi...
Question: 6.12

Verified Answer:

Use a Python dictionary. Arrays are great when you...
Question: 6.13

Verified Answer:

Use the Python [] notation. Use the key of the ent...
Question: 6.10

Verified Answer:

Use the [:] Python language construction. The foll...
Question: 6.7

Verified Answer:

Use the for Python language command: >>&g...
Question: 6.2

Verified Answer:

Use the [] notation to access elements of a list b...
Question: 6.3

Verified Answer:

Use the len Python function. For example: >&...