Page 335 - Computer Science Class 11 With Functions
P. 335
The strings 'red', 'green', 'blue', 'pink', 'orange', 'white', and 'black' are stored at
index 0, 1, 2, 3, 4, 5, and 6, respectively. The indexes 0, 1, 2, 3, 4, 5, 6, correspond to the negative indexes
-7, -6, -5, -4, -3, -2, and -1, respectively. To access an element in a list, the list object is followed by an opening square
bracket, the index to be accessed, and a closing square bracket. For example,
>>> colors[3]
'pink'
>>> colors[-2]
'white'
Unlike strings, lists are mutable. So, we can replace an item in a list with another item. For example,
>>> colors[3] = 'yellow'
>>> colors
['red', 'green', 'blue', 'yellow', 'orange', 'white', 'black']
13.1.1 List Derived from a String
Given a string as an argument, the list() function returns a list. For example,
>>> vowels = 'aeiou'
>>> list(vowels)
['a', 'e', 'i', 'o', 'u']
13.1.2 Length of a List: len()
We have already used the len() function to find the length of a string. We can also apply the len() function to
find the number of elements in a list. For example,
>>> len(colors)
7
13.1.3 Slicing
In the last chapter, we used slicing for accessing a subsequence of elements in a string. In this chapter, we will use
slicing to access the subsequences of lists and tuples. Recall the following syntax for specifying a slice:
<start>:<finish> [:<step>]
Note that the step is optional. Below we give some examples of slicing,
>>> colors[3:6]
['yellow', 'orange', 'white']
The slice [3:6] yields a list comprising the elements colors[3], colors[4], and colors[5], but not
colors[6].
The slice [:3] yields the list comprising the list elements up to index 3 (excluding the element at index 3, For example,
>>> colors[:3]
['red', 'green', 'blue']
Note that colors[-1] and colors[6] refer to the same position in list colors. So, the slice [1, -1] yields
the list comprising the list elements colors[1], colors[2], …, colors[5] excluding colors[6].
>>> colors[1:–1]
['green', 'blue', 'yellow', 'orange', 'white']
The slice [::2] yields a list, comprising the alternate elements of the list, because the step size is 2:
>>> colors[::2]
['red', 'blue', 'orange', 'black']
The slice [1:7:3] yields a list, comprising the elements beginning at index 1 and up to index 7 (excluding the
element at index 7), in steps of size 3. Thus, the expression colors[1:7:3] yields a list comprising the elements
colors[1] and colors[4]:
>>> colors[1:7:3]
['green', 'orange']
Lists and Tuples 333

