I have a problem with the for loop Python

Question:

I have a problem when using the for loop, I don’t know why my loop is not working as expected.

CODE:

class Solution:
    def searchInsert(nums, target):
        pos = 0
        for i in nums:
            if nums[pos] != target:
                pos = pos + 1
                
            print(pos)
            break

Solution.searchInsert([1,3,5,6], 5)

This program receives an array of integers and another integer which I call target, the script has to give me back the position in the array in which we have the number of the target.

In this case my array "nums" contains [1,3,5,6] and my target is 5, so the result must be 2, because the number of the target (5) is in the position "2" of the array.

The problem comes when I run the script. Instead of a 2 the script gives me a 1

If someone catches the error in the code please tell me.

Asked By: Pablo

||

Answers:

you could use enumerate which gives you the index and value

class Solution:
    def searchInsert(nums, target):
        for index, value in enumerate(nums):
            if value == target:
                return index 
             
print(Solution.searchInsert([1,3,5,6], 5))
Answered By: JL Houss

You are closing the loop after the first iteration: you need to add an else: block so it can keep going until the condition is met…

class Solution:
    def searchInsert(nums, target):
        pos = 0
        for i in nums:
            if nums[pos] != target:
                pos = pos + 1
            else:    
                print(pos)
                break
>>> Solution.searchInsert([1,3,5,6],5)
2
Answered By: Pythoneer

I am posting here just fixed code but as others pointed out, its a strange way to deal with it. But I understand, if you learn Python and come from other language (Visual Basic?), one would go this way.
In python indent is crucial. In your code, you need to increase pos everytime code goes through cycle, not only when you find/did not find the value you want.

class Solution:
    def searchInsert(nums, target):
        pos = 0
        for i in nums:
            if nums[pos] == target:
                print(pos) #replace with return pos ?
                break
            pos = pos + 1 #increase outside above condition

Solution.searchInsert([1,3,5,6], 5)

To make this code easier, one liner, investigate other users comments. Or research array index, length and later pandas module.

Answered By: bracko