0

What is the difference between these 2 fragments of python codes?
I want to check whether an array contains the integers 1,2,3 in sequence as its elements?

def arrayCheck(nums):
    for i in nums:
        if(i <= (len(nums)-3)):
            if (nums[i] == 1 and nums[i+1] == 2 and nums[i+2] == 3):
                return(True)
    return(False)

def arrayCheck(nums):
    for i in range(0,len(nums)-2):
        if (nums[i] == 1 and nums[i+1] == 2 and nums[i+2] == 3):
            return(True)
    return(False)

The first one gives wrong answer for the array:

arrayCheck([1,1,2,1,1,1,1,2,3])

but the second one is correct.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • 4
    `for i in nums:` isn't iterating over the indices, it is iterating over the actual list items. – miradulo Jun 03 '18 at 13:47
  • for i in nums: here "i" does not contain the index value, "i" contains list items value. "in" operator iterates over items, not indices. let input is [1,1,2,1,1,1,1,2,3]. In the first iteration, i=1,i+1=2,i+2=3 so, nums[1]=1 nums[2]=2 nums[3]=1 . . . . . In the last iteration, again,i=1,i+1=2,i+2=3 and again you're accessing nums[1],nums[2] and nums[3]! But you expected to check nums[6],nums[7],nums[8]. Every time when i=1 you are accessing the indices 1,2 and 3.That's why you're getting this error. In the second function you're accessing the index values,so it's working. – Taohidul Islam Jun 03 '18 at 15:38

1 Answers1

1

The first block i is elements of the parameter. The second, it's only their indices.

If you wanted the first to iterate over indices rather than the elements, use this

def arrayCheck(nums):
    for i, _ in enumerate(nums):
        if i <= len(nums)-3:

You can also use list slicing, by the way

if nums[i:i+2] == [1,2,3]:
    return True 
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245