A Comprehensive Introduction to Python Programming and ... - MSDL
A Comprehensive Introduction to Python Programming and ... - MSDL
A Comprehensive Introduction to Python Programming and ... - MSDL
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
1.2 Language Features 9 / 75<br />
>> list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]<br />
>> list[1:7]<br />
[1, 2, 3, 4, 5, 6]<br />
>><br />
It is possible <strong>to</strong> assign a list <strong>to</strong> a slice <strong>to</strong> modify part of an existing list, as shown<br />
below. Assigning an empty list <strong>to</strong> a slice deleted the slice from the original list.<br />
Listing 4: Slice Assignment<br />
>> list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]<br />
>> list[1:6] = [’a’, ’b’]<br />
[0, ’a’, ’b’, 6, 7, 8, 9, 10]<br />
>><br />
The colon opera<strong>to</strong>r has some interesting defaults. When its left-h<strong>and</strong> side is not<br />
specified, it defaults <strong>to</strong> 0. When its right-h<strong>and</strong> side is not specified, it defaults <strong>to</strong> the<br />
length of the list. Therefore, the <strong>Python</strong> instruction list name[:] will return the<br />
entire list.<br />
The built-in function len( ) can be used <strong>to</strong> obtain the length of a list. It is also<br />
possible <strong>to</strong> concatenate lists by using the ’+’ opera<strong>to</strong>r.<br />
1.2.4.2 Tuples<br />
Tuples simply consist of a series of values enclosed within parentheses. Here is an<br />
example of a tuple:<br />
(’arial’, 10, ’bold’)<br />
Tuples work exactly like lists, except for the fact that they are immutable, which<br />
means that their elements cannot be modified in place. However, the values s<strong>to</strong>red in<br />
the components of a tuple can be modified. In other words, a tuple should be thought<br />
of as holding references (or pointers) <strong>to</strong> other objects. Consider the following two<br />
examples. The first one shows that trying <strong>to</strong> change the elements of a tuple is not<br />
allowed. The second one shows that it is possible <strong>to</strong> modify a mutable element which<br />
is inside of a tuple. Note the fundamental difference between the two examples.<br />
Listing 5: Tuple Example 1<br />
>> list = [’a’, ’f’, ’c’]<br />
>> tuple = (10, list, ’string constant’)<br />
>> tuple[1]<br />
[’a’, ’f’, ’c’]<br />
>> tuple[1] = [’some’, ’other’, ’list’] 5