0

Essentially, I am trying to make a function which reads an array, and a number. If the number is within the array, it should return True, and False otherwise. However, I find that for each element in the array there is a True or False - the code checks everything individually, when I only need one True or False; is the number in the array or not ?

def is_it_there(arr, k):
    for x in arr:
        if x == k:
            print(True)
        else:
            print(False)

is_it_there([8,5,2,234,426,7,11],11)

Like I said before, only one True was expected, but each item was checked and so it was False, False, False, False, False, False, True

1
  • 1
    What about print(k in arr)? Commented Apr 10, 2019 at 21:24

5 Answers 5

6

It's just

if k in arr:
   print(True)
else:
   print(False)

or, simpler

print(k in arr)
Sign up to request clarification or add additional context in comments.

Comments

0

The problem rises from the fact because you are checking it constantly while looping through the elements. So the code is going to check through constantly whether or not the element is present or not. So you are going to end up printing a statement everytime. Python gives a neat way to do achieve this

def is_it_there(arr, k):
    if k in arr:
       print(True)
    else:
       print(False)

is_it_there([8,5,2,234,426,7,11],11)

Comments

0

You can refactor your code like this:

def is_it_there(arr, k):
    for x in arr:
        if x == k
            return True
    return False

print(is_it_there([8,5,2,234,426,7,11],11))

Comments

0

If you find the item anywhere in the list, print True and exit the function immediately.

If you make it all the way to the end of the list without finding it, only then print False.

def is_it_there(arr, k):
    for x in arr:
        if x == k:
            # print True and terminate the function
            print(True)
            return
    # if we made it all the way through the loop, we didn't find it
    print(False)

However, the 'in' operator already does what you want:

if value in mylist:
    print 'True'
else:
    print 'False'

Comments

0

You are printing a result each time you do a test in your loop. Try to record the result of each round of your test in a list, and test if there is any "True" value in your result list.

Code Example:

def is_it_there(arr, k):
    result = list()
    for x in arr:
        if x == k:
            result.append(True)
        else:
            result.append(False)
    if True in  result:
        print(True)
    else:
        print(False)
is_it_there([8,5,2,234,426,7,11],11)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.