Lucas
Lucas

Reputation: 3715

Add item into array if not already in array

How can I insert item into the array if its not already there?

This is what I tried:

    [..]
    k = []
    for item in myarray:
        if not item in k:
             print("Item is in array already.")
             k[] = item

Upvotes: 19

Views: 68057

Answers (3)

Patch Rick Walsh
Patch Rick Walsh

Reputation: 457

If you don't care about the order of the items in the list, you can convert it to a set to filter out any duplicates.

k = list(set(myarray))

Or if k already contains something...

k = [...]  # optionally non-empty array
k = list(set(k) | set(myarray))

What that does is convert both myarray and k into sets, and combines them so that the result is a unique list that containing the contents of both k and myarray.

Upvotes: 2

Chad
Chad

Reputation: 1864

Your code has the right idea but just use k.append(item) instead of k[] = item.

Also it is cleaner to say if item not in k:

Upvotes: 34

TerryA
TerryA

Reputation: 59974

k[] = item is invalid syntax. All you need to do is just remove that line and use list.append()

for item in myarray:
    if not item in k:
        print("Item is in array already.")
        k.append(item)

list.append() adds an item to the end of the list.

Upvotes: 11

Related Questions