Farhan.K
Farhan.K

Reputation: 3485

How to find 2 items in a list that are the same in Python

I have a list populated with ~100 names. The names in this list either occur once or twice and I would like to go through the list to find names that occur twice and names that only occur once. I will also need the position of the reoccurring names in the list and the positions of the names that only appear once.

I'm not sure how I would go about doing this because all the methods I can think of are inefficient as they would go through the whole list even if they have already found a match. Other methods that I can think of would return two duplicate positions. The names that occur twice will not necessarily be adjacent to each other.

For example, if this was the list:

mylist = [ 1, 2, 3, 1, 4, 4, 5, 6]

I would need something that outputs (something like):

[[0,3],[1],[2],[4,5],[6],[7]]

With those numbers being the positions of the duplicate names and the position of the names that occur once.

I am by no means an expert so any help would be appreciated.

Upvotes: 2

Views: 358

Answers (2)

Kasravnd
Kasravnd

Reputation: 107287

You can use enumerate to get the pairs contain index of each element and the element itself then loop over it and store the items as key and indices as values using a collections.OrderedDict (to preserve the order) and dict.setdefault method:

>>> from collections import OrderedDict
>>> d=OrderedDict()
>>> for i,j in enumerate(mylist):
...     d.setdefault(j,[]).append(i)
... 

>>> d.values()
[[0, 3], [1], [2], [4, 5], [6], [7]]

Upvotes: 4

Arijoon
Arijoon

Reputation: 2300

I would use a dictionary:

mylist = [1,2,3,1,4,4,5,6]
dic = {}

for i in range(0,len(mylist)):
    if mylist[i] in dic:
        dic[mylist[i]].append(i)
    else:
        dic[mylist[i]] = [i]
print dic.values()
# prints [[0, 3], [1], [2], [4, 5], [6], [7]]

Upvotes: 1

Related Questions