Python error "cannot unpack non-iterable int object"

I want to get the indexes of the elements in the list which add up to the sum.

numbers = [10,2,3,5,8,200]
sum = 12

for i,v in numbers:
    if i+v == sum:
        print(numbers[i]), print(numbers[v])

But I get this error:

Traceback (most recent call last):
  File "C:\User\User\PycharmProjects\training\", line 9, in <module>
    for i,v in numere:
TypeError: cannot unpack non-iterable int object

>Solution :

This is the infamous Two Sum problem on LeetCode, and As LeetCode states :

We can do it in one-pass. While we are iterating and inserting elements into the hash table, we also look back to check if current element’s complement already exists in the hash table. If it exists, we have found a solution and return the indices immediately.

def twoSum(nums: List[int], sum: int) -> List[int]:
        hashmap = {}
        for i in range(len(nums)):
            complement = sum - nums[i]
            if complement in hashmap:
                return [i, hashmap[complement]]
            hashmap[nums[i]] = i

 x = twoSum(nums=numbers, sum=sum)

Leave a Reply