How to Search and Sort Lists in Python - dummies

By John Paul Mueller

You can do many things with lists. As a Python programmer, you have lots of options. Those lists may not do you much good if you don’t know what is in the list. To make that job even easier, you can sort lists to make information easier to find.

Searching lists

Modifying a list isn’t very easy when you don’t know what the list contains. The ability to search a list is essential if you want to make maintenance tasks easier. The following steps help you create an application that demonstrates the ability to search a list for specific values.

  1. Open a Python File window.

    You see an editor in which you can type the example code.

  2. Type the following code into the window — pressing Enter after each line:

    Colors = ["Red", "Orange", "Yellow", "Green", "Blue"]
    ColorSelect = "
    while str.upper(ColorSelect) != "QUIT":
     ColorSelect = input("Please type a color name: ")
     if (Colors.count(ColorSelect) >= 1):
      print("The color exists in the list!")
     elif (str.upper(ColorSelect) != "QUIT"):
      print("The list doesn't contain the color.")

    The example begins by creating a list named Colors that contains color names. It also creates a variable named ColorSelect to hold the name of the color that the user wants to find. The application then enters a loop where the user is asked for a color name that is placed in ColorSelect. As long as this variable doesn’t contain the word QUIT, the application continues a loop requesting input.

    Whenever the user inputs a color name, the application asks the list to count the number of occurrences of that color. When the value is equal to or greater than one, the list does contain the color and an appropriate message appears onscreen. On the other hand, when the list doesn’t contain the requested color, an alternative message appears onscreen.

    Notice how this example uses an elif clause to check whether ColorSelect contains the word QUIT. This technique of including an elif clause ensures that the application doesn’t output a message when the user wants to quit the application. You need to use similar techniques when you create your applications to avoid potential user confusion or even data loss (when the application performs a task the user didn’t actually request).

  3. Choose Run→Run Module.

    You see a Python Shell window open. The application asks you to type a color name.

  4. Type Blue and press Enter.

    image0.jpg

    You see a message telling you that the color does exist in the list.

  5. Type Purple and press Enter.

    image1.jpg

    You see a message telling you that the color doesn’t exist.

  6. Type Quit and press Enter.

    The application ends. Notice that the application displays neither a success nor a failure message.

Sorting lists

The computer can locate information in a list no matter what order it appears in. It’s a fact, though, that longer lists are easier to search when you put them in sorted order. However, the main reason to put a list in sorted order is to make it easier for the human user to actually see the information the list contains. People work better with sorted information.

This example begins with an unsorted list. It then sorts the list and outputs it to the display. The following steps demonstrate how to perform this task.

  1. Open a Python File window.

    You see an editor in which you can type the example code.

  2. Type the following code into the window — pressing Enter after each line:

    Colors = ["Red", "Orange", "Yellow", "Green", "Blue"]
    for Item in Colors:
     print(Item, end=" ")
    print()
    Colors.sort()
    for Item in Colors:
     print(Item, end=" ")
    print()

    The example begins by creating an array of colors. The colors are currently in unsorted order. The example then prints the colors in the order in which they appear. Notice the use of the end=” “ argument for the print() function to ensure that all color entries remain on one line (making them easier to compare).

    Sorting the list is as easy as calling the sort() function. After the example calls the sort() function, it prints the list again so that you can see the result.

  3. Choose Run→Run Module.

    You see a Python Shell window open. The application outputs both the unsorted and sorted lists.

    image2.jpg

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()