0

Here's the code part :-

arr=[1,2,3,4,5,6,1,2,3,4,5,6]

and say I want to search 5 and print it's index.

x=Number to be searched 
for i in range(len(arr)):
    if x==arr[i]:
        print("Found at",i)
else:
    print("Not found")

The output is as follows :-

Found at 4
Found at 10
Not found

Hoe to get rid of the last line ? It should not be printed as 5 is present in arr! Note : I just started learning python few days ago so I'm sorry if this is a trivial question but I can't get the reason of it printing that one.

5
  • So you don't seem to need the else part then. Commented Oct 22, 2019 at 16:58
  • 1
    Ah, I see that I changed your indentation when fixing your code for proper formatting. The else: branch of a for loop is executed when you reach the end. You can stop the else branch from executing by using break. But you can't break out of the loop here. Don't use else:, use a flag variable or counter. Commented Oct 22, 2019 at 17:00
  • What if someone searched an item not present in the array? It should handle some error message . Commented Oct 22, 2019 at 17:01
  • 1
    @Epsilonzero set a flag that you set to True when you stuble upon the desired number. Then in a condition outside of the main for loop, if the flag is False, then print your "Not found" message. Commented Oct 22, 2019 at 17:03
  • Thanks Brian, that worked. Commented Oct 22, 2019 at 17:08

1 Answer 1

1

You can't use else: here, because for:...else: executes the else branch when you reach the end of the loop. You can only prevent this by using break in the for loop so it doesn't reach the end. You cant usebreak` here because you want to show all matching values.

You have two options:

  • Use a flag variable to remember that you found matches; set it to True when you have a match:

    found = False  # flag variable, defaulting to 'nothing found'
    for i in range(len(arr)):
        if x==arr[i]:
            print("Found at", i)
            found = True  # found at least one match, set the flag to true
    if not found:
        print("Not found")
    
  • Gather all indices into a list first, before printing. If the list is empty, you know didn't find anything:

    indices = []
    for i in range(len(arr)):
        if x==arr[i]:
            indices.append(i)
    
    if indices:
        for index in indices:
            print('Found at:', index)
    else:
        print("Not found")
    

That last option can be achieved more concisely with a single list comprehension and the enumerate() function:

indices = [i for i, value in enumerate(arr) if value == x]
if indices:
    for index in indices:
        print("Found at", index)
else:
    print("Not found")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.