How do I print only non repeated elements in a list in Python?

Viewed 4689

I've an array arr = [4, 8, 2, 8, 9].

I want to print the elements that doesn't repeat.

i.e. 4, 2, 9

but my code is giving list index out of range even though the same logic is working in Java but not in my Python code. Here is my code:

def odd_occurring_num(arr):
    count = 0
    size = len(arr)
    
    for i in arr:
        for j in arr:
            if (arr[i] == arr[j] and i != j):
                break
        if (j == size):
            count += 1
    return count
    
# driver Code
arr = [4, 8, 2, 8, 9]
print(odd_occurring_num(arr))
2 Answers

You don't even need to import modules, Python has it all built in

arr = [4, 8, 2, 8, 9]
def odd_occurring_num(arr):
    return [i for i in arr if arr.count(i) < 2]

print(odd_occurring_num(arr))

what you did:

for i in arr:
    arr[i] = ...

will actually iterate through the items of array, so you are getting arr[4] which is 9, then arr[8] which is not defined as you list is only 5 elements. What you can do is:

for i, elem in enumerate(arr):
   arr[i] = ...

which will iterate over the index i and the elements itself

Try this:

from collections import Counter                                                                                                                                                                                                                                                   

c = Counter([4, 8, 2, 8, 9])    
[i for i,j in c.items() if j==1]

This will returns:

[4, 2, 9]

Also if you take a look at c you can see:

Counter({4: 1, 8: 2, 2: 1, 9: 1})
Related