Maxxx
Maxxx

Reputation: 3768

Appending value into list without duplicates

I have a list of integers containing:

intlist = [19,4,2,4]

and i want to append the value from the intlist into a list of list such that:

noDuplist = [[19,0],[4,1],[2,2]]

where the first index represents the value from the intlist and the second index represents the index of the value in the intlist. 19 is at index 0, 4 is at index 1 and 2 is at index 2. Since there is another 4 i do not want to include that since i didn't want duplicate hence the last 4 is just going to be left out.

I tried something like:

noDuplist = []
for i in range(len(intlist)):
    if intlist[i] not in noDuplist:
        noDuplist.append([intlist[i],i])

but I'm still getting

[[19, 0], [4, 1], [2, 2], [4, 3]]

where the [4,3] shouldnt be there. Would appreciate some help on this

Upvotes: 0

Views: 451

Answers (2)

arjoonn
arjoonn

Reputation: 988

I assume you want to retain the indices from the original sequence. Thus what you want is something that remembers at what index was the value first seen in the original sequence.

The problem is in your condition since

if intlist[i] not in noDuplist:
   # something

would check if 4 was present in [[19, 0], [4, 1], [2, 2]]] which it isn't.

A cleaner way of doing this could be using dictionaries or sets.:

intlist = [19,4,2,4]
seen_so_far, noDuplist = set(), []

for i, v in enumerate(intlist):
    if v not in seen_so_far:
        noDuplist.append([v, i])
        seen_so_far.add(v)

print(noDuplist)

Which gives the output [[19, 0], [4, 1], [2, 2]]

Upvotes: 1

Eric Le Fort
Eric Le Fort

Reputation: 2716

The first thing I'd suggest is not bothering storing the index as well as the value. You'll know the index when extracting elements anyway.

The first approach that comes to my mind (not sure if it's optimal) involves using a dictionary in combination with your list. Whenever you try to insert a value, check if it exists in your dictionary. If it doesn't, add it to the dictionary and your list. If it does, don't add it.

This would result in O(N) complexity.

Edit: I didn't read your description thoroughly enough. Since you need the index from the original array, simply enter both as a key/value pair into your dictionary instead.

Upvotes: 0

Related Questions