LanguagesLearn to Program Using Python: Lists, Part I

Learn to Program Using Python: Lists, Part I

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.




Preface

This document is part of a series of online tutorial lessons designed to teach you how to program using the Python scripting language.

Something for everyone

Beginners start at the beginning, and experienced programmers jump in further along.

Introduction

What you have learned

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.

What is a Subscription?

I referred to a subscription as an index in the lesson on strings.

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 discuss 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.

aStr
= “This is a string”


print aStr[0]

print aStr[3]

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.


What is a Sequence?

Python provides three kinds of sequences: strings, lists, and tuples.

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.

>>>
aStr = “xyz”


>>> print aStr[-1]

z

>>>

Figure 2

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

>>>
aString = “xyz”


>>> print aString[-1]

z

>>> print aString[-2]

y

>>> print aString[-3]

x

>>> print aString[-4]

Traceback (innermost
last):


  File “<stdin>”,
line 1, in ?


IndexError: string index
out of range


>>>

Figure 3

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.


What is a Mapping?

A mapping is a structure in which values are stored and retrieved according to a key.  This is often called a dictionary, because it behaves similarly to a common dictionary.

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.


What is a Slicing?

I discussed slicings at some length in the lesson on strings, using a different source for my information.  In this lesson, I will paraphrase information extracted from the Python Reference Manual.

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.

print
aStr[0:4


print aStr[10:16

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.

print
aStr[:4


print aStr[10:

Figure 5

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.

print
aStr[-5:-2]

Figure 6

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.


What is a Mutable Sequence?

According to the Python Reference Manual, “Mutable sequences can be changed after they are created. The subscription and slicing notations can be used as the target of assignment and del (delete) statements.”

There is currently a single mutable sequence type in Python, and it is a List.


What is a List?

According to the Reference Manual, “The items of a list are arbitrary Python objects. Lists are formed by placing a comma-separated list of expressions in square brackets.”

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.


Some Sample Programs

Creating, indexing, and slicing lists

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.

#
File Lists01.py


# Rev 2/4/00

# Copyright 2000, R.
G. Baldwin


# Illustrates creating, 

#  indexing, and
slicing lists.


#

#——————————-

theList = [3.14,59,”A
string”,


          
1024]


print “Print index value
2”


print theList[2]

print “Print a short
slice”


print theList[0:3]

print “Print the entire
list”


print theList[:100]

Figure 7

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.

D:BaldwinAA-SchoolPyProg>python
Lists01.py


Print index value 2

A string

Print a short slice

[3.14, 59, ‘A string’]

Print the entire list

[3.14, 59, ‘A string’, 1024]

D:BaldwinAA-SchoolPyProg>

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.

#
File Lists02.py


# Rev 2/4/00

# Copyright 2000, R.
G. Baldwin


# Illustrates concatenating 

#  lists

#

#——————————-

print “Create two lists”

listA = [3.14,59,”A
string”,


          
1024]


listB = [2,4,6,16]

print “Print listA”

print listA

print “Print listB”

print listB

print “Concatenate the
lists”


listC = listA + listB

print “Print concatenated
list”


print listC

Figure 9

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.

D:BaldwinAA-SchoolPyProg>python
Lists02.py


Create two lists

Print listA

[3.14, 59, ‘A string’, 1024]

Print listB

[2, 4, 6, 16]

Concatenate the lists

Print concatenated list

[3.14, 59, ‘A string’, 1024,
2, 4, 6, 16]

D:BaldwinAA-SchoolPyProg>

Figure 10

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.

#
File Lists03.py


# Rev 2/4/00

# Copyright 2000, R.
G. Baldwin


# Illustrates mutating
lists


#

#——————————-

print “Create and print
a list”


listA = [3.14,59,”A
string”,


          
1024]


print listA

print “Modify the list”

listA[2] = “New string”

print “Print the modified
list”


print listA

print “Modify the list
again”


listA[3] = listA[3]
* 2


print “Print the modified
list”


print listA

print “Modify the list
again”


listA[2] = 0.99999

print “Print the modified
list”


print listA

Figure 11

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

D:BaldwinAA-SchoolPyProg>python
Lists03.py


Create and print a list

[3.14, 59, ‘A string’, 1024]

Modify the list

Print the modified list

[3.14, 59, ‘New string’,
1024]


Modify the list again

Print the modified list

[3.14, 59, ‘New string’,
2048]


Modify the list again

Print the modified list

[3.14, 59, 0.99999, 2048]

D:BaldwinAA-SchoolPyProg>

Figure 12

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.


Review

1.  A subscription is how you go about getting magazines delivered to your mailbox, True or False?

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.

theList
= [3.14,59,”A string”,


          
1024]

Figure 13

15.  Show how to access an item in a list using a subscription.

Ans:  See Figure 14.

print
theList[2]

Figure 14

16.  Show how to access a slice from a list.

Ans:  See Figure 15.

print
theList[0:3]

Figure 15

17.  Show how to concatenate two lists.

Ans:  See Figure 16.

listA
= [3.14,59,”A string”,


          
1024]


listB = [2,4,6,16]

listC = listA + listB

Figure 16

18.  Show how to modify an item in a list using a subscription.

Ans:  See Figure 17.

listA
= [3.14,59,”A string”,


          
1024]

listA[2] = “New string”

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.

About the author

Richard Baldwin is a college professor and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

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.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories