Page 186 - Information_Practice_Fliipbook_Class11
P. 186
For example,
>>> colors[3]
'pink'
>>> colors[-2]
'white'
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']
7.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']
7.1.2 Length of a list: len()
We can apply the len() function to find the number of elements in a list. For example,
>>> len(colors)
>>> 7
7.1.3 Slicing
We can use slicing for accessing a subsequence of elements in a list. The following syntax is used 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']
172 Touchpad Informatics Practices-XI

