Home > database >  python int object is not iterable
python int object is not iterable

Time:07-05

I am trying to find a duplicate number in the python program, but I am getting an error int object is not iterable

class Solution:
def duplicates(self, arr, n): 
    for i in arr:
        a = arr.count(i)
        if a >= 2:
            return i
    else:
        return -1
   
  if(__name__=='__main__'):
t = int(input())
for i in range(t):
    n = int(input())
    arr = list(map(int, input().strip().split()))
    res = Solution().duplicates(arr, n)
    for i in res:
        print(i,end=" ")
    print()

CodePudding user response:

Note: I'm assuming this is a programming exercise. This is by far not the most efficient nor the fastest-to-code way to figure out if there are duplicate items in a list.

The error occurs in this for loop:

res = Solution().duplicates(arr, n)
for i in res:
    print(i,end=" ")

Looking at Solution().duplicates(), res will always be an integer; not a list of integers, nor a list containing a single integer. You cannot iterate over it.

You could replace the block above with:

res = Solution().duplicates(arr, n)
print(res, end=" ")
  • Related