I am a beginner to coding, and I am wondering why my code below doesn't work. The problem is from HackerRank - LonelyInteger, it is to identify the unique number in an array where other numbers occur twice.
For example, the input of [1, 2, 3, 4, 3, 1, 2] would give the result of 4.
May I ask why doesn't my code below work?
My thinking is to create a new 'test' list to store the numbers. When there is a new number, the 'test' list store that number, and when it encounters the number again, it deletes that number, leaving behind the unique number. However, when I run the code, the list is empty. Can anyone explain why is this?
def lonely_integer(a):
test = []
for i in a:
if i not in test:
test.append(i)
if i in test:
test.remove(i)
print(test)
lonely_integer([1, 1, 2])