sequences of values.
Enter 10 integers: Enter integer 1:
5.4.4 Sequence Slicing
We have discussed how to create sequences and access them through the [] operator (to access one element) or a for statement (to access all the elements iteratively). Sometimes, a program may need to access a series of sequential values (e.g., the characters of a person’s last name in a string that stores the person’s full name). For these cases, Python allows pro- grams to slice a sequence.
Figure 5.8 demonstrates Python sequence-slicing capabilities. The program creates three sequences—a string, a tuple and a list. The program prompts the user to enter a starting and ending index, creates the specified slice for each sequence and prints the slice to the screen. 18 print "\nUnpacking tuple..."
19 first, second, third = aTuple
20 print "Tuple values:", first, second, third 21
22 # swapping two values 23 x = 3
24 y = 4
25
26 print "\nBefore swapping: x = %d, y = %d" % ( x, y ) 27 x, y = y, x # swap variables
28 print "After swapping: x = %d, y = %d" % ( x, y ) Unpacking string... String values: a b c Unpacking list... List values: 1 2 3 Unpacking tuple... Tuple values: a A 1 Before swapping: x = 3, y = 4 After swapping: x = 4, y = 3 Fig. 5.7 Fig. 5.7 Fig. 5.7
Fig. 5.7 Unpacking strings, lists and tuples. (Part 2 of 2.)
1 # Fig. 5.8: fig05_08.py 2 # Slicing sequences. 3 Fig. 5.8 Fig. 5.8 Fig. 5.8
4 # create sequences
5 sliceString = "abcdefghij"
6 sliceTuple = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ) 7 sliceList = [ "I", "II", "III", "IV", "V", 8 "VI", "VII", "VIII", "IX", "X" ] 9
10 # print strings
11 print "sliceString: ", sliceString 12 print "sliceTuple: ", sliceTuple 13 print "sliceList: ", sliceList 14 print
15
16 # get slices
17 start = int( raw_input( "Enter start: " ) ) 18 end = int( raw_input( "Enter end: " ) ) 19
20 # print slices
21 print "\nsliceString[", start, ":", end, "] = ", \ 22 sliceString[ start:end ]
23
24 print "sliceTuple[", start, ":", end, "] = ", \ 25 sliceTuple[ start:end ]
26
27 print "sliceList[", start, ":", end, "] = ", \ 28 sliceList[ start:end ]
sliceString: abcdefghij
sliceTuple: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
sliceList: ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'] Enter start: 3 Enter end: 3 sliceString[ 3 : 3 ] = sliceTuple[ 3 : 3 ] = () sliceList[ 3 : 3 ] = [] sliceString: abcdefghij sliceTuple: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
sliceList: ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X']
Enter start: -4 Enter end: -1
sliceString[ -4 : -1 ] = ghi sliceTuple[ -4 : -1 ] = (7, 8, 9)
sliceList[ -4 : -1 ] = ['VII', 'VIII', 'IX']
Fig. 5.8 Fig. 5.8 Fig. 5.8
Lines 5–18 create the three sequences and request the user to specify a beginning and ending index for the slice. Lines 21–28 print the specified slice for each sequence. A slice is simply a new sequence, created from an existing sequence. The expression in line 22
sliceString[ start:end ]
creates (slices) a new sequence from variable sliceString. This new sequence contains the values stored at indices sliceString[ start ], …, sliceString[ end - 1 ]. In general, to obtain from sequence a slice of the ith element through the jth element, inclu- sive, use the expression
sequence[ i:j + 1 ]
Figure 5.8 includes three sample outputs from the program. The first sample creates a slice from indices 0 to 10 (e.g., the entire sequence). Recall that the first element in every sequence is the zeroth element. The sequence created from this slice is equivalent to the sequence created with the expression
sequence[ : ]
This expression creates a new sequence that is a copy of the original sequence. The above expression is equivalent to the following expressions:
sequence[ 0 : len( sequence ) ] sequence[ : len( sequence ) ] sequence[ 0 : ]
The syntax for sequence slicing provides a useful shortcut for selecting a portion of an existing sequence. A program can use sequence slicing to create a copy of a list when passing the list to a function. We discuss this issue in Section 5.7 and 5.8.
Note that negative slices cannot access the last element of a list directly (i.e.,slice-
String[ -4 : -1 ] = ghi) because slices apply to points between elements. With neg- ative slices, the last point between elements is the point between elements with indices -2 and -1.
sliceString: abcdefghij
sliceTuple: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
sliceList: ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X']
Enter start: 0 Enter end: 10
sliceString[ 0 : 10 ] = abcdefghij
sliceTuple[ 0 : 10 ] = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
sliceList[ 0 : 10 ] = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X']
Fig. 5.8 Fig. 5.8 Fig. 5.8
5.5 Dictionaries
In addition to lists and tuples, Python supports another powerful data type, called the dic- tionary. Dictionaries (called hashes or associative arrays in other languages) are mapping constructs consisting of key-value pairs. Dictionaries can be thought of as unordered col- lections of values where each value is referenced through its corresponding key. For exam- ple, a dictionary might store phone numbers that can be referenced by a person’s name.
The statement
emptyDictionary = {}
creates an empty dictionary. Notice that curly braces ({}) denote dictionaries. To initialize key-value pairs for a dictionary, use the statement
dictionary = { 1 : "one", 2 : "two" } Each key-value pair is of the form
key : value
A comma separates each key-value pair. Dictionary keys must be immutable values, such as strings, numbers or tuples. Dictionary values can be of any Python data type.
Common Programming Error 5.3
Using a list or a dictionary for a dictionary key is an syntax error. 5.3
Figure 5.9 demonstrates how to create, initialize, access and manipulate simple dictio- naries. Lines 5–6 create and print an empty dictionary. Line 9 creates a dictionary grades and initializes the dictionary to contain four key-value pairs. The keys are strings that con- tain student names, and the integer values represent the students’ grades. Line 10 prints the value assigned to variable grades. Observe that the application displays grades in a dif- ferent order than the declaration; this is because a dictionary is an unordered collection of key-value pairs. Also, notice in the output that the dictionary keys appear in single quotes, because Python displays strings in single quotes.
1 # Fig. 5.09: fig05_09.py
2 # Creating, accessing and modifying a dictionary. 3
4 # create and print an empty dictionary 5 emptyDictionary = {}
6 print "The value of emptyDictionary is:", emptyDictionary 7
8 # create and print a dictionary with initial values
9 grades = { "John": 87, "Steve": 76, "Laura": 92, "Edwin": 89 } 10 print "\nAll grades:", grades
11
12 # access and modify an existing dictionary
13 print "\nSteve's current grade:", grades[ "Steve" ] 14 grades[ "Steve" ] = 90
15 print "Steve's new grade:", grades[ "Steve" ] Fig. 5.9
Fig. 5.9 Fig. 5.9
Line 13 accesses a particular dictionary value, using the [] operator. Dictionary