Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether elements appears in the list only once in python?

I have a list:

a = [1, 2, 6, 4, 3, 5, 7]

Please, explain to me how to check whether element appears only once in in the list?

Please, also explain if all elements from 1 to len(a) are in the list. For instance, in list 'a' element from 1 to 7 are in the list, but if the list is b = [1, 4, 3, 5], then not all elements from 1 to 4 are not in the list.

Thank you!

like image 586
Bob Avatar asked Oct 10 '10 09:10

Bob


3 Answers

len( set( a ) ) == len( a )

for the first question, and

( len( set( a ) ) == len( a ) == max( a ) ) and min( a ) == 1

for the second.

like image 87
poke Avatar answered Sep 19 '22 23:09

poke


When I read your question, I took a different meaning from it than mark did. If you want to check if a particular element appears only once, then

def occurs_once(a, item):
    return a.count(item) == 1

will be true only if item occurs in the list exactly once.

See Pokes answer for the second question

like image 25
aaronasterling Avatar answered Sep 20 '22 23:09

aaronasterling


For your first question if your elements are hashable you can create a set containing the elements and check its length:

len(set(a)) == len(a)

Alternatively you can use this function which can give better performance than the above if the result is False (but worse performance when the result is True):

def are_all_elements_unique(l):
    seen = set()
    for x in l:
        if x in seen:
            return False
        seen.add(x)
    return True
like image 21
Mark Byers Avatar answered Sep 20 '22 23:09

Mark Byers