• No results found

and c[ 2 ]contains the value 6453 To calculate the sum of the values contained in the first three elements of sequence c and assign the result to variable sum, we would write

In document Python - How to Program (Page 160-163)

sequences of values.

72 and c[ 2 ]contains the value 6453 To calculate the sum of the values contained in the first three elements of sequence c and assign the result to variable sum, we would write

sum = c[ 0 ] + c[ 1 ] + c[ 2 ]

To divide the value of the seventh element of sequence c by 2 and assign the result to the variable x, we would write

x = c[ 6 ] / 2

Common Programming Error 5.1

It is important to note the difference between the “seventh element of the sequence” and “se- quence element seven.” Sequence subscripts begin at 0, thus the “seventh element of the se- quence” has a subscript of 6. On the other hand, “sequence element seven” references subscript 7 (i.e., c[ 7 ]), which is the eighth element of the sequence. This confusion often

leads to “off-by-one” errors. 5.1

Testing and Debugging Tip 5.1

In other programming languages that do not allow negative subscripts, if a negative sub- script is accidentally calculated, a run-time error occurs. In Python, such an accidental neg- ative subscript could cause a non-fatal logic error, with the program running to completion

and producing invalid results. 5.1

The pair of square brackets enclosing the subscript of a sequence is a Python operator. Figure 5.2 shows the precedence and associativity of the operators introduced to this point in the text. They are shown from top to bottom in decreasing order of precedence, with their associativity and types.

5.3 Creating Sequences

Different Python sequences (strings, lists and tuples) require different syntax. We illustrat- ed how Python strings are created by placing the text of the string within quotes. To create an empty string, use a statement like

aString = ""

Note that we could have used single quotes (') or triple quotes (""" or ''') to create the string.

To create an empty list, use a statement like aList = []

To create a list that contains a sequence of values, separate the values by commas inside square brackets ([])

aList = [ 1, 2, 3 ]

To create an empty tuple, use the statement aTuple = ()

To create a tuple that contains a sequence of values, simply separate the values with com- mas.

aTuple = 1, 2, 3

Creating a tuple is sometimes referred to as packing a tuple. Tuples also can be created by surrounding the comma-separated list of tuple values with optional parentheses. It is the commas that create tuples, not the parentheses.

aTuple = ( 1, 2, 3 )

When creating a one-element tuple—called a singleton—use a statement like aSingleton = 1,

Notice that a comma (,) follows the value. The comma identifies the variable—

aSingleton—as a tuple. If the comma were omitted, aSingleton would simply con- tain the integer value 1.

5.4 Using Lists and Tuples

Lists and tuples both contain sequences of values. For example, a list or a tuple may contain the sequence of integers from 1 to 5

Operators Associativity Type

() left to right parentheses

[] left to right subscript

. left to right member access

** right to left exponentiation

* / // % left to right multiplicative

+ - left to right additive

< <= > >= left to right relational

== != <> left to right equality

Fig. 5.2 Fig. 5.2Fig. 5.2

aList = [ 1, 2, 3, 4, 5 ] aTuple = ( 1, 2, 3, 4, 5 )

In practice, however, Python programmers distinguish between the two data types to rep- resent different kinds of sequences, based on the context of the program. In the next sub- sections, we discuss the situations for which lists and tuples are best suited.

5.4.1 Using Lists

Although lists are not restricted to homogeneous data types (i.e., values of the same data type), Python programmers typically use lists to store sequences of homogeneous values. For example, either a list may store a sequence of integers that represent test scores or a sequence of strings representing employee names. In general, a program uses a list to store homogeneous values for the purpose of looping over these values and performing the same operation on each value. Usually, the length of the list is not predetermined and may vary over the course of the program. The program in Fig. 5.3 demonstrates how to create, aug- ment and retrieve values from a list.

1 # Fig. 5.3: fig05_03.py

2 # Creating, accessing and changing a list. 3

4 aList = [] # create empty list 5

6 # add values to list

7 for number in range( 1, 11 ): 8 aList += [ number ]

9

10 print "The value of aList is:", aList 11

12 # access list values by iteration

13 print "\nAccessing values by iteration:"

14

15 for item in aList: 16 print item, 17

18 print 19

20 # access list values by index

21 print "\nAccessing values by index:"

22 print "Subscript Value"

23

24 for i in range( len( aList ) ):

25 print "%9d %7d" % ( i, aList[ i ] ) 26

27 # modify list

28 print "\nModifying a list value..."

29 print "Value of aList before modification:", aList 30 aList[ 0 ] = -100

31 aList[ -3 ] = 19

32 print "Value of aList after modification:", aList Fig. 5.3

Fig. 5.3 Fig. 5.3

Line 4 creates empty list, aList. Lines 7–8 use a for loop to insert the values 1, …, 10 into aList, using the += augmented assignment statement. When the value to the left of the += statement is a sequence, the value to the right of the statement also must be a sequence. Thus, line 8 places square brackets around the value to be added to the list. Line 10 prints variable aList. Python displays the list as a comma-separated sequence of values inside square brackets. Variable aList represents a typical Python list—a sequence containing homogeneous data.

Lines 13–18 demonstrate the most common way of accessing a list’s elements. The

for structure actually iterates over a sequence for item in aList:

The for structure (lines 15–16) starts with the first element in the sequence, assigns the value of the first element to the control variable (item) and executes the body of the for loop (i.e., prints the value of the control variable). The loop then proceeds to the next ele- ment in the sequence and performs the same operations. Thus, lines 15–16 print each ele- ment of aList.

List elements also can be accessed through their corresponding indices. Lines 21–25 access each element in aList in this manner. The function call in line 24

range( len( aList ) )

returns a sequence that contains the values 0, ..., len( aList ) - 1. This sequence con- tains all possible element positions for aList. The for loop iterates through this se- quence and, for each element position, prints the position and the value stored at that position.

The value of aList is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Accessing values by iteration:

1 2 3 4 5 6 7 8 9 10

In document Python - How to Program (Page 160-163)