Python Programming Lesson #28
July 19, 2000
Something for everyone
Beginners start at the beginning, and experienced programmers jump in further along. Lesson 1 provides an overall description of this online programming course.
You have been moving along rather briskly in learning how to program using Python. For example, in an earlier lesson you learned how to index and slice strings.
Introducing lists
In this lesson, we will extend that knowledge to a new type of data called a list. This type of data, along with a string, is referred to as a sequence.
A little backtracking
First, however, I want to nail down some terminology from the Python reference manual.
The following discussion of a subscription is based on the Python Reference Manual.
So, what does a subscription do?
A subscription selects an item of a sequence (string, tuple or list) or mapping (dictionary) object, as in the following:
primary "[" expression_list "]"
Don't panic! This is not as complicated as it appears, as you will see shortly.
(I discussed strings earlier. I will tuples, lists, and mappings later.)
What is the primary?
According to the Reference Manual, the primary must evaluate to an object of a sequence or mapping type.
For example, in the lesson on strings, the primary was a reference to a string named aStr, as shown in Figure 1.
Will continue to call it an index
I will probably continue to refer to a subscription as an index most of the time, simply because I believe that index is the more commonly recognized term.
I discussed strings in a previous lesson. I will discuss lists in this lesson, and I will discuss tuples in a future lesson.
What about the expression_list?
According to the Reference Manual, if the primary is a sequence, the "expression_list" must evaluate to a plain integer.
An example of an integer expression_list
In the string example above, the plain integer was 0 in one case and 3 in the other.
Negative integers
If the (index) value is negative, the length of the sequence is added to it to obtain the actual index used to access the sequence.
For example, aSequence[-1] selects the last item of the sequence.
Example negative integer
This is illustrated in the interactive code fragment shown in Figure 2, which prints the last character in a string.
More negative-integer rules
The value resulting from adding the length of the sequence to the specified index value must be a non-negative integer less than the number of items in the sequence.
Then, the subscription selects the item whose index is that value (counting from zero).
Good and bad negative integers
This is illustrated in the interactive code fragment shown in Figure 3, which shows both valid and invalid negative subscription values. (The subscription value of -4 violates the above rule, thus producing an IndexError.)
What about a character type?
There is no character type in Python. Rather, a string's items are characters. A character is not a separate data type but a string of exactly one character.
A real dictionary example
For example, if I want to know about the word Python, I get out my Webster's Seventh New Collegiate Dictionary, (which is about forty years old), and I look up the word python (in this case, python is the key).
The (approximate) value associated with the key is, "... monstrous serpent killed by Apollo ..."
Is this a definition?
In normal conversation, we frequently refer to the value obtained from a common printed dictionary as the definition of the word. However, definition usually means something completely different in computer jargon.
In computer jargon, we refer to it as the value associated with the word (key). Thus, a mapping, is a structure that associates values with keys.
So, a common printed dictionary is an example of a mapping.
No mention of the Python language
Since my dictionary is much older than the Python programming language, I wouldn't expect to find anything about Python programming there.
What about the expression_list?
According to the Reference Manual, if the primary is a mapping, the expression_list must evaluate to an object whose value is one of the keys of the mapping (such as python in my common dictionary example).
What gets selected?
Then the subscription selects the value in the mapping that corresponds to that key.
In other words, the system looks up the word in the dictionary and returns the value that corresponds to that word.
More to say about mappings
I will have more to say about mappings in a future lesson.
The semantics for a simple slicing are as described in the following paragraphs.
What about the primary?
To begin with, the primary must evaluate to a sequence object (a string, a list, or a tuple). In other words, a dictionary structure cannot be sliced.
A slicing specifies two numeric bounds
The lower and upper bound expressions, if present, must evaluate to plain integers, such as in the statements from the lesson on strings shown in Figure 4.
What about default values?
Both the lower and upper bounds have default values. The default values are zero and the sequence's length, respectively.
Figure 5 shows some examples of using default values from the lesson on strings.
What about negative bounds?
If either bound is negative, the sequence's length is added to it. The slicing then selects all items with index k such that i <= k < j where i and j are the specified lower and upper bounds.
This may be an empty sequence. It is not an error if i or j lie outside the range of valid indexes (such items don't exist so they aren't selected).
An example of negative bounds
Figure 6 shows an example of the use of negative bounds from the previous lesson on strings.
Reducing confusion
The previous lesson on strings also contains a diagram from Guido van Rossum that helps to clarify the complexity surrounding the use of negative values when slicing. If this discussion on negative indices is confusing, you might want to go back and take a look at that diagram.
There is currently a single mutable sequence type in Python, and it is a List.
Now, for a less formal discussion
The above discussion may have seemed a little heavy for an online programming course aimed at beginning programmers. However, there are certain things that we must define in a reasonably formal way in order to continue to make progress.
The remainder of this lesson will be a little less formal, and more in the style that you have come to expect in this set of programming tutorials.
A list can be written as a sequence of comma-separated values (items) surrounded by square brackets.
Lists can be nested within other lists.
List items do not all have to be of the same type.
An example list
The short Python script shown in Figure 7 creates a simple list containing four elements of different types. The types of the elements are respectively, a float value, an integer, a string, and another integer.
Print an item using a subscription
After creating the list, the program uses a subscription (index) to extract and print the value at index 2 (remember the first item is at index 0).
Print some slices
Then it uses the slice notation to extract and print two different slices from the list.
The first slice extracts and prints the elements from index 0 through index 2 inclusive. (Remember, the items selected by a slice do not include the index specified by the upper limit value, which is 3 in this case.)
The second slice extracts and prints the entire list. If you don't understand these two slices, go back and review the lesson on strings where I discuss slicing in detail.
Program output
The output from this program is shown in Figure 8.
Lists can be concatenated
Lists can be concatenated using the + operator.
The Python program shown in Figure 9 creates two lists and prints them both. Then it concatenates the two lists and prints the concatenated version.
Program output
The output from this program is shown in Figure 10 (boldface added for emphasis). As you can see, the concatenated list contains the elements of both of the individual lists.
Lists are mutable
Unlike strings, the values in a list can be modified after the list is created.
The Python program shown in Figure 11 creates and prints a list. Then it uses a subscription to modify and print the list three times.
Replace a string with another string
The first modification replaces an existing string in the list with a new string.
Multiply an integer element by two
The second modification multiplies an integer value in the list by a factor of two.
Replace a string by a float
The third modification replaces a string in the list by a float value of 0.99999.
Program output
The output from the program is shown in Figure 12 (boldface added for emphasis).
More to come
There is a lot more for you to learn about lists that is not included in the above discussion. I will continue this discussion of Lists, including more sample programs, in a future lesson. Now it is time to review what we have learned so far.
Ans: False in the Python context. In Python, A subscription selects an item of a sequence object.
2. Name three types of sequence objects.
Ans: string, tuple and list
3. Given the following nomenclature
primary "[" expression_list "]"
what is the requirement for the primary?
Ans: The primary must evaluate to an object of a sequence or mapping type.
4. If the primary is a sequence, what must be the type of expression_list?
Ans: If the primary is a sequence, the expression_list
must evaluate to a plain
integer.
5. In question 4 above, the integer must be positive, True or False?
Ans: False. The integer may be positive or negative.
6. Which item in the sequence is selected for an index value of -1?
Ans: The last item in the sequence is selected for an index value of -1.
7. Just like C, C++, and Java, Python supports a character type, True or False?
Ans: False. There is no character type in Python. Rather, a string's items are characters. A character is not a separate data type but a string containing exactly one character.
8. What is another name for a mapping?
Ans: A dictionary.
9. What must be the type of the primary (see the above nomenclature) in order to support the use of slicing.
Ans: The primary must evaluate to a sequence object for the use of slicing.
10. What is a mutable sequence?
Ans: Mutable sequences can be changed after they are created.
11. A string is a mutable sequence, True or False?
Ans: False. The characters in a string cannot be modified after the string is created. There is currently a single mutable sequence type in Python, and it is a list.
12. What kinds of items can be placed in a list?
Ans: The items of a list are arbitrary Python objects.
13. How are lists formed?
Ans: Lists are formed by placing a comma-separated sequence of expressions in square brackets.
14. Show how to create a simple list using program code.
Ans: See Figure 13.
15. Show how to access an item in a list using a subscription.
Ans: See Figure 14.
16. Show how to access a slice from a list.
Ans: See Figure 15.
17. Show how to concatenate two lists.
Ans: See Figure 16.
18. Show how to modify an item in a list using a subscription.
Ans: See Figure 17.
Copyright 2000, Richard G. Baldwin. Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.
Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two. He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas. He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.
Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.
-end-