0

What happens when you search for 35 in the list [10,20,30,40,50]?

To simplify this i'll just post the options,

1.The program would handle the case by printing a suitable message that the element is not found

2.The value 30 is returned as it is the closest number less than 35 that is present in the list

3.The value 40 is returned as it is the closest number greater than 35 that is present in the list

4.The program will abruptly come to an end without intimating anything to the user.

  • 5
    Well, that depends on *how* you search for it. All of the above options can be implemented. – user2390182 Sep 11 '18 at 15:21
  • Welcome to StackOverflow. Please take a look at the site's [tour](http://stackoverflow.com/tour) and [How to Ask](http://stackoverflow.com/help/how-to-ask) to ask better questions. The question is a task to be written, and should include at least your attempt to solve the problem and not simply ask for a solution. – chickity china chinese chicken Sep 11 '18 at 17:07

1 Answers1

1

Alright, so this statement will return False.

35 in [10,20,30,40,50]

What you can then do is expand on this however you want, if you want it to print whether or not it is in the list as such:

if 35 in [10,20,30,40,50]:
    print("Element found in list")
else:
    print("Element not found in list")

In python, when you search for an item in a list in this way, it will return a Boolean (True or False), it will not return anything else unless you want it to by programming it to do so.

If you do want to implement something like finding the closest item in a list to your search query, you could do it like this (Stolen from https://stackoverflow.com/a/12141207/8593865):

def findClosest(myNumber, myList):
    return min(myList, key=lambda x:abs(x-myNumber))

If you just want to do something if an item is not in a list:

if 35 not in [10,20,30,40,50]:
    #Do something
0rdinal
  • 641
  • 4
  • 17