Home > Software engineering >  looping over a list/arry: for item in list vs for item in range (0, len(list)) both showing differen
looping over a list/arry: for item in list vs for item in range (0, len(list)) both showing differen

Time:01-19

Code: 1

class Solution:
    def firstElementKTime(self,  a, n, k):
        # code here
        countDict = {}
        for i in a:
            if (a[i] in countDict):
                countDict[a[i]] = countDict[a[i]]   1
            else:
                countDict[a[i]] = 1
        for i in a:
            if countDict[a[i]] == k:
                return a[i]
        return -1

Error of Code 1: Traceback (most recent call last): File "/home/91ded90adaf6c5d579e2dbec3cedff79.py", line 40, in main() File "/home/91ded90adaf6c5d579e2dbec3cedff79.py", line 34, in main print(ob.firstElementKTime(a, n, k)) File "/home/91ded90adaf6c5d579e2dbec3cedff79.py", line 9, in firstElementKTime if (a[i] in countDict): IndexError: list index out of range

Code: 2

        countDict = {}
        for i in range(0, len(a)):
            if a[i] in countDict:
                countDict[a[i]] = countDict[a[i]]   1
            else:
                countDict[a[i]] = 1
            i = i   1
        for i in a:
            if countDict[a[i]] == k:
                return a[i]
        return -1

No error:

I expect same behavior in both of the above code..

CodePudding user response:

The first one is running on a’s elements, and not on the indexes. So a[i] is like a[a[0]] in the first iteration.

for i in a

Will give you a[0], a[1], …

CodePudding user response:

If you expect same behaviour in both the codes the:

in Code 1 you have to remove the indices part1:

class Solution:
    def firstElementKTime(self,  a, n, k):
        # code here
        countDict = {}
        for i in a:
            if (a in countDict):
                countDict[a] = countDict[a]   1
            else:
                countDict[a] = 1
        for i in a:
            if countDict[a] == k:
                return a
        return -1

Since for i in a: will directly access element without index while in Code 2 you are accessing with indices.

  • Related