CHAPTER 5
In the previous chapters we’ve addressed string, integer, float, and Boolean data types. In this chapter we’ll look at lists, a data type that holds an organized collection of items. The items, or values, that are contained within the list can be various data types themselves. In fact, you can even have lists that exist within lists.
Note that lists are created by using comma separated values between square brackets. The pattern is list_name = [item_1, item_2, item_N]. To create an empty list use: list_name = []. Items within a list can always be accessed by index. List indices are always zero based, which means that the first item in the list will have an index of 0, the second item an index of 1, and so on. To access any item in a list using an index, simply enclose the index in square brackets directly following the list name. The pattern is list_name[index].
Code Listing 147
animals = ['toad', 'lion', 'seal'] print(animals[0]) print(animals[1]) print(animals[2]) |
Output:
Code Listing 148
toad lion seal |
Keep in mind that not only can you access values by index, you can also set values by index.
Code Listing 149
animals = ['toad', 'lion', 'seal'] print(animals[0]) animals[0] = 'sheep' print(animals[0]) |
Output:
Code Listing 150
toad sheep |
Also, you can access items starting at the end of the list by making use of a negative index. The -1 index will represent the last item on the list, with -2 representing the second to last item on the list, and so on.
Code Listing 151
animals = ['toad', 'lion', 'seal'] print(animals[-1]) print(animals[-2]) print(animals[-3]) |
Output:
Code Listing 152
seal lion toad |
To add an item to the end of a list use the append() method and pass in the item that you wish to add.
Code Listing 153
animals = ['toad', 'lion', 'seal'] animals.append('fox') print(animals[-1]) |
Output:
Code Listing 154
fox |
If you wish to add multiple items to the end of a list, use the extend() method. The extend() method takes a list. You pass in a list by name or create one by surrounding a list of items within brackets.
Code Listing 155
animals = ['toad', 'lion', 'seal'] animals.extend(['fox', 'owl']) print(animals) more_animals = ['whale', 'elk'] animals.extend(more_animals) print(animals) |
Output:
Code Listing 156
['toad', 'lion', 'seal', 'fox', 'owl'] ['toad', 'lion', 'seal', 'fox', 'owl', 'whale', 'elk'] |
It is also possible to add a single item at any point in the list simply by making use of the insert() method. Pass in the index where you want to add the item, follow it with a comma, and then the item itself. All of the current items in the list will be moved over by one.
Code Listing 157
animals = ['toad', 'lion', 'seal'] animals.insert(0, 'whale') print(animals) animals.insert(2, 'owl') print(animals) |
Output:
Code Listing 158
['whale', 'toad', 'lion', 'seal'] ['whale', 'toad', 'owl', 'lion', 'seal'] |
To access a selected portion of a list, which can be referred to as a slice, specify two indices and then separate them with a colon placed within brackets. The slice will begin at the first index and go up to, but not include, the very last index. If the first index is omitted then 0 is assumed. If the second index is omitted the number of items in the list is implied.
Code Listing 159
animals = ['toad', 'lion', 'seal', 'fox', 'owl', 'whale'] some_animals = animals[1:4] print('Some animals: {}'.format(some_animals)) first_two = animals[0:2] print('First two animals: {}'.format(first_two)) first_two_again = animals[:2] print('First two animals: {}'.format(first_two_again)) last_two = animals[4:6] print('Last two animals: {}'.format(last_two)) last_two_again = animals[-2:] print('Last two animals: {}'.format(last_two_again)) |
Output:
Code Listing 160
Some animals: ['lion', 'seal', 'fox'] First two animals: ['toad', 'lion'] First two animals: ['toad', 'lion'] Last two animals: ['owl', 'whale'] Last two animals: ['owl', 'whale'] |
It is possible to use slices with strings. Just think of a string as a list of characters.
Code Listing 161
part_of_a_whale = 'whale'[1:3] print(part_of_a_whale) |
Output:
Code Listing 162
ha |
Keep in mind that the index() method will accept a value as a parameter and then return the index of the first value on the list. For example, if there were two incidences of lion in the animals list, then animals.index('lion') would return the index of the first occurrence of lion. If the value is not discovered on the list, then Python will raise an exception.
Code Listing 163
animals = ['toad', 'lion', 'seal'] lion_index = animals.index('lion') print(lion_index) |
Output:
Code Listing 164
1 |
An exception is most often a clear indication that something has either unexpectedly occurred, or has just generally gone wrong within your program. If you don't account for, or handle exceptions within, your program, Python will print out a message which explains the exception, as well as halt the execution of the program. The following is an example of an exception that hasn’t been handled.
Code Listing 165
animals = ['toad', 'lion', 'seal'] sheep_index = animals.index('sheep') print(sheep_index) |
Output:
Code Listing 166
Traceback (most recent call last): File "exception_example.py", line 2, in <module> sheep_index = animals.index('sheep') ValueError: 'sheep' is not in list |
These messages that Python provides can be a valuable resource for correcting mistakes that exist within your code. As you can see from the previous example, Python clearly displayed the line number as well as the code that caused the exception.
A key thing to remember though is that you often need to prevent Python from exiting whenever it encounters an exception. In order to avoid this you need to tell your program what it should do whenever it encounters an exception. Do this by surrounding any code you think may raise an exception in a try/except block. Let's update the previous example with a try/except block.
Code Listing 167
animals = ['toad', 'lion', 'seal'] try: sheep_index = animals.index('sheep') except: sheep_index = 'No sheep found.' print(sheep_index) |
Output:
Code Listing 168
No sheep found. |
If any exception is raised while you are executing the code in the try: code block, the code in the except: code block will be executed. If no exception is met in the try: code block, the code in the except: code block is omitted and will not be executed.
If you are looking to perform an action on every item in a list, use a for loop. The pattern you will use is for item_variable in list_name:. Like if statements and function definitions, the for statement will always end in a colon. The code block that follows the for statement will be executed for every item within the list. Effectively what happens is that the first item in the list, list[0], is assigned to item_variable and the code block is executed. The next item in the list, list[1], is assigned to item_variable and the code block is executed. This process lasts until the list is finished. If there are no items in the list, the code block will not be executed.
The following example prints the uppercase version of every item in the animals list.
Code Listing 169
animals = ['toad', 'lion', 'seal'] for animal in animals: print(animal.upper()) |
Output:
Code Listing 170
TOAD LION SEAL |
In addition to the for loop, Python also has a while loop. The pattern is while condition: followed by a code block. As long as this condition evaluates to true, the code block following the while statement will be executed. Typically, the code block will modify a variable that is part of the condition. At some point the condition will evaluate to false and the program continues after the while loop. In cases where the condition never evaluates to false it will become an infinite loop. To halt the execution of a Python program press Ctrl+C. Ctrl+C will allow you an out if you accidentally create an infinite loop, breaking you out of your program.
The following example creates an index variable to store an integer, and will be employed as the index of the animals list. The while loop will execute when the index is less than the length of the animals list. During the code block the index variable will be incremented by one. The plus-equals operator adds a value to the variable's existing value, and assigns the new value to that variable. Using index += 1 will increment the index variable by one. Note that unlike many programming languages, Python does not have a "++" increment operator.
Code Listing 171
animals = ['toad', 'lion', 'seal', 'fox', 'owl', 'whale', 'elk'] index = 0 while index < len(animals): print(animals[index]) index += 1 |
Output:
Code Listing 172
toad lion seal fox owl whale elk |
To sort a list, call the sort() method on the list, making sure to avoid using any arguments. This will reorder the current list. If you wish to create a new list, simply use the built-in sorted() function and provide a list as an argument.
Code Listing 173
animals = ['toad', 'lion', 'seal'] sorted_animals = sorted(animals) print('Animals list: {}'.format(animals)) print('Sorted animals list: {}'.format(sorted_animals)) animals.sort() print('Animals after sort method: {}'.format(animals)) |
Output:
Code Listing 174
Animals list: ['toad', 'lion', 'seal'] Sorted animals list: ['lion', 'seal', 'toad'] Animals after sort method: ['lion', 'seal', 'toad'] |
To concatenate or combine two or more lists, use the plus sign.
Code Listing 175
animals = ['toad', 'lion', 'seal'] more_animals = ['fox', 'owl', 'whale'] all_animals = animals + more_animals print(all_animals) |
Output:
Code Listing 176
['toad', 'lion', 'seal', 'fox', 'owl', 'whale'] |
To determine the number of items on a list, use the built-in len()function and pass in a list.
Code Listing 177
animals = ['toad', 'lion', 'seal'] print(len(animals)) animals.append('fox') print(len(animals)) |
Output:
Code Listing 178
3 4 |
Another important built-in function is the range() function, which creates a list of numbers and is often combined with the for statement. This function is useful when you want to complete an action a given number of times, or when you want to have access to the index of a list.
The range() function necessitates at least one parameter that will denote a stop. By default, range() produces a list that begins at zero and continues up to, but not including, the stop. To generate a list that encompasses N items, pass N to range() like so: range(N). For example, if you want to get a list of 4 items use range(4). The list starts at zero and will contain the numbers 0, 1, 2, and 3.
Code Listing 179
for number in range(4): print(number) |
Output:
Code Listing 180
0 1 2 3 |
It is possible for you to define the start as well as the stop. The pattern is range(start, stop). To begin a list at 2 and stop at 4, use range(2, 4). This will produce a list that is made up of only two items, 2 and 3.
Code Listing 181
for number in range(2, 4): print(number) 2 3 |
In addition to the start and stop parameters, the range() function is also capable of accepting a step parameter. In cases where all three parameters are being utilized, the list will begin at the start value, cease just before the stop value, and increment the list by the step value. If there is no step value specified, as in the previous examples, its default value is 1. Let's try generating a list that incorporates all of the even numbers from 0 to 8.
Code Listing 182
for number in range(0, 10, 2): print(number) |
Output:
Code Listing 183
0 2 4 6 8 |
The following is an example of using the range() function in conjunction with a list to print every other item in that list.
Code Listing 184
animals = ['toad', 'lion', 'seal', 'fox', 'owl', 'whale', 'elk'] for number in range(0, len(animals), 2): print(animals[number]) |
Output:
Code Listing 185
toad seal owl elk |
Lists can be made using square brackets to enclose comma separated values. The pattern is list_name = [item_1, item_2, item_N].
An index can be used to access items in a list. List indices are zero based. The pattern is list_name[index].
Use negative indices to access items from the end of the list. The last item in a list is list_name[-1].
Items can be added to a list by using the append() or extend() list methods.
A slice allows you to access a portion of a list. The pattern is list_name(start, stop)
The list index() method will accept a value as a parameter and return the index of the first value in the list, or create an exception if the value is not found within the list. The pattern is list_name.index(value).
Loop through a list by utilizing a for loop. The pattern is for item_variable in list_name: followed by a code block.
The code block in a while loop will execute as long as the condition evaluates to true. The pattern is while condition: followed by a code block.
To sort a list, use the built-in sorted() function or the sort() list method.
The built-in range() function will produce a list of numbers. The pattern is range(start, stop, step).
Unhandled exceptions will cause Python programs to terminate. You can avoid this by handling exceptions using try/except blocks.
Try creating a Python program that will capture and display a person's grocery shopping list. Make it so the program will continually prompt the user for another item until the point where they enter a blank item. After all the items have been entered, try displaying the shopping list back to the user.
Sample Output:
Code Listing 186
Enter an item for your grocery list. Press <ENTER> when done: bread Item added. Enter an item for your grocery list. Press <ENTER> when done: milk Item added. Enter an item for your grocery list. Press <ENTER> when done: coffee Item added. Enter an item for your grocery list. Press <ENTER> when done: Your Grocery List: ------------------ bread milk coffee |
Code Listing 187
# Create a list to hold the grocery items. grocery_list = [] finished = False while not finished: item = input('Enter an item for your grocery list. Press <ENTER> when done: ') if len(item) == 0: finished = True else: grocery_list.append(item) print('Item added.') # Display the grocery list. print() print('Your Grocery List:') print('-' * 18) for item in grocery_list: print(item) |
Data Structures (Lists): https://docs.python.org/3/tutorial/datastructures.html
Exceptions: https://docs.python.org/3/library/exceptions.html
For Loops: https://wiki.python.org/moin/ForLoop
Handling Exceptions: https://wiki.python.org/moin/HandlingExceptions
Sorted: https://docs.python.org/3/library/functions.html#sorted
While Loops: https://wiki.python.org/moin/WhileLoop