Page 195 - Information_Practice_Fliipbook_Class11
P. 195
• 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
7.7.1 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 7.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 7.2(b) shows a failed linear search for the key 10 in the same list.
(a) Searching for 37
(b) Searching for 10
Fig 7.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. If it reaches the end of the list without finding
the key, the program returns False.
Program 7.1: Linear Search
01 '''
02 Objective: To search for a key in a list
03 User Interface:
04 1.User is asked to enter a list
05 2.The user is asked to enter the key, and the program reports the search
06 result. This is repeated so long as the user wants to continue.
07 '''
08
09 myList = eval(input('Enter a list:\n'))
10 print('List:', myList)
11 while True:
12 key = int(input('Enter the number to be searched:'))
Python Lists 181

