Page 196 - Information_Practice_Fliipbook_Class11
P. 196
13 found = False
14 for index in range(len(myList)):
15 if myList[index] == key:
16 found = True
17
18 if found:
19 print(key,' is present in the list at index', index)
20 else:
21 print(key,' is not present in the list')
22 searchAgain = input('Continue another search? say Y/y for yes, N/n for no:')
23 if searchAgain != 'Y' and searchAgain != 'y':
24 break
The result of executing Program 7.1 on a sample input list of size 15 is shown in Fig 7.3. The program begins by creating
an empty list myList. First, the user is prompted to enter a list of numbers. Suppose the user enters the elements
14, 6, 1, 8, 14, 50, 61, 89, 37, 109, 3, 21, 89, 90, 60 to the list myList (line 9). The
eval()function used in this statement is a built-in function of Python that takes a string comprising an expression.
If it finds a valid expression, it evaluates it and yields the result; otherwise, it raises Syntax Error for a syntactically
incorrect expression. So the myList will be assigned the list [14, 6, 1, 8, 14, 50, 61, 89, 37, 109,
3, 21, 89, 90, 60]. Next, on the execution of line 12, the user is prompted to enter the key to be searched
(say, 37). In line 13, the program initially sets the variable found as False, indicating that the key is not yet found.
It then successively compares the key with the elements at index 0, 1, 2, … until the key is found (line 15) or we reach
the end of the list (line 18). If the search is successful (i.e., the condition in line 15 yields True), the program returns
True along with the index of the search key. Thus, when we searched for key 37 (Fig. 7.3), the program returned True
along with index 8. Now the program displays the following message (line 19):
37 is present in the list at index 8
However, if, on examining the entire list, the control comes out of the loop without finding the key, we conclude
that the search key does not appear in the list. Thus, when we search for key 10 (Fig. 7.3), the following message is
displayed (line 21):
10 is not present in the list
Sample output:
>>> Enter a list:
[14, 6, 1, 8, 14, 50, 61, 89, 37, 109, 3, 21, 89, 90, 60]
List: [14, 6, 1, 8, 14, 50, 61, 89, 37, 109, 3, 21, 89, 90, 60]
>>> Enter the number to be searched:37
37 is present in the list at index 8
Continue another search? say Y/y for yes, N/n for no:Y
>>> Enter the number to be searched:10
10 is not present in the list
Continue another search? say Y/y for yes, N/n for no:n
Fig 7.3: An execution of Program 7.1
Creating a Sorted List
The function sorted() returns a sorted list comprising the elements of the list passed as argument, but without
modifying it.
>>> lst = ['Physics', 'Chemistry', 'Maths', 'Computer Sc.']
>>> sorted(lst)
['Chemistry', 'Computer Sc.', 'Maths', 'Physics']
>>> lst
['Physics', 'Chemistry', 'Maths', 'Computer Sc.']
182 Touchpad Informatics Practices-XI

