ben
ben

Reputation: 665

Search through list with duplicates

I have a list that looks like this:

 list1 = [1,2,4,6,8,9,2]

If I were to say

 if 2 in list1:
      print True

It prints True once. Is there a way to determine if 2 or any variable x is in the list multiple times and if so how many without iterating through the entire list like this?

for item in list1:
      if item = 2:
          duplicates +=1

Upvotes: 0

Views: 129

Answers (6)

inspectorG4dget
inspectorG4dget

Reputation: 113905

Collections.counter (as others have pointed out) is how I would do this. However, if you really want to get your hands dirty:

def count(L):
    answer = {}
    for elem in L:
        if elem not in answer:
            answer[elem] = 0
        answer[elem] += 1
    return answer

>>> counts = count(myList)
>>> duplicates = [k for k,v in counts.iteritems() if v>1]

Upvotes: 0

Joel Cornett
Joel Cornett

Reputation: 24788

I would use a collections.Counter object for this:

from collections import Counter
myCounter = Counter(list1)

print myCounter[2] > 1 #prints 'True'

If you only plan on doing this with one or a few elements of the list, I would go with abarnert's answer, however.

Upvotes: 1

Akavall
Akavall

Reputation: 86128

list1 = [1,2,4,6,8,9,2]

dict1 = {}

for ele in list1:
    # you iterate through the list once
    if ele in dict1:
        # if a key is already in the dictionary
        # you increase the corresponding value by one
        dict1[ele] += 1 
    else:
        # if a key is not yet in the dictionary
        # you set its corresponding value to one
        dict1[ele] = 1

Result:

>>> dict1
{1: 1, 2: 2, 4: 1, 6: 1, 8: 1, 9: 1}

Upvotes: 0

ogzd
ogzd

Reputation: 5692

from collections import Counter
y = Counter(list1)
print y[2]
print y[5] # and so on

Upvotes: 4

ben_frankly
ben_frankly

Reputation: 9940

list1 = [1,2,4,6,8,9,2]
print list1.count(2)

Upvotes: 1

abarnert
abarnert

Reputation: 365587

I think you're looking for list.count:

if list1.count(2) > 1:
    print True

In Sequence Types:

s.count(i) total number of occurrences of i in s

Of course under the covers, the count method will iterate through the entire list (although it will do so a lot faster than a for loop). If you're trying to avoid that for performance reasons, or so you can use a lazy iterator instead of a list, you may want to consider other options. For example, sort the list and use itertools.groupby, or feed it into a collections.Counter, etc.

Upvotes: 7

Related Questions