Page 309 - Beginning Programming with Pyth - John Paul Mueller
P. 309
You may need to sort items in reverse order at times. To
accomplish this task, you use the reverse() function. The function must
appear on a separate line. So the previous example would look like this
if you wanted to sort the colors in reverse order:
Colors = ["Red", "Orange", "Yellow", "Green", "Blue"]
for Item in Colors:
print(Item, end=" ")
print()
Colors.sort() Colors.reverse() for Item in Colors:
print(Item, end=" ")
print()
Printing Lists
Python provides myriad ways to output information. In fact, the number of ways would amaze you. This chapter has shown just a few of the most basic methods for outputting lists so far, using the most basic methods. Real-world printing can become more complex, so you need to know a few additional printing techniques to get you started. Using these techniques is actually a lot easier if you play with them as you go along.
1. Type the following code into the notebook — pressing Enter after
each line:
Colors = ["Red", "Orange", "Yellow", "Green", "Blue"]
print(*Colors, sep='\n')
This example begins by using the same list of colors in the previous section. In that section, you use a for loop to print the individual items. This example takes another approach. It uses the splat (*) operator, also called the positional expansion operator (and an assortment of other interesting terms), to unpack the list and send each element to the print() method one item at a time. The sep argument tells how to separate each of the printed outputs, relying on a newline character in this case.
2. Click Run Cell.