Page 298 - Computer Science Class 11 Without Functions
P. 298
The del statement can also be used to remove an element from the list by specifying its index.
>>> del lst[3]
>>> lst.pop()
55
>>> lst
[10, 20, 30, 50, 20, 60, 20, 30]
Delete a Slice: You can also use the del statement to remove a slice of elements from the list.
myList = [10, 20, 30, 40, 50]
del myList[1:4] # Removes elements at index 1, 2, and 3 (20, 30, 40)
print(myList) # Output: [10, 50]
Delete Entire List: If you want to completely remove the entire list and free up the memory it occupies, you can use
the del statement without specifying an index.
myList = [10, 20, 30]
del myList # Deletes the entire list
# Now myList is not defined and will raise an error if used
12.9 Linear Search
Often, we are required to check whether a given value appears in a list. The value to be searched is called the key.
Given a key to be searched in a list, we successively compare it with the elements at index 0, 1, 2, … until the key is
ultimately found or we reach the end of the list. In the former case, we announce that the search was successful and
report its position (i.e., index) in the list. If the search fails, we report that the key is not present in the list. As the search
key is sequentially compared with the elements in the list, this method of searching for a key is called sequential search
or linear search.
Fig 12.2(a) shows a successful linear search for the key 37 in the list [14, 6, 1, 8, 14, 50, 61, 89, 37,
109, 3, 21, 89, 90, 60]. Fig 12.2(b) shows a failed linear search for the key 10 in the same list.
(a) Searching for 37
(b) Searching for 10
Fig 12.2: Linear Search
Having understood the linear search algorithm, we are ready to develop a program (see Program 7.1) that takes a list
myList and a value key to be searched in myList as inputs from the user. When the key is present in myList,
the program outputs True and the index where the search key is found.
296 Touchpad Computer Science-XI

