Bob
Bob

Reputation: 10815

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!

Upvotes: 9

Views: 22648

Answers (5)

Johannes Charra
Johannes Charra

Reputation: 29953

For the second question you might want to check

sorted(a) == range(1, len(a) + 1)

Upvotes: 4

Ant
Ant

Reputation: 5424

i understood you want something like that:

[x for x in a if a.count(x) == 1]

Upvotes: 4

aaronasterling
aaronasterling

Reputation: 71064

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

Upvotes: 9

poke
poke

Reputation: 388313

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

for the first question, and

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

for the second.

Upvotes: 7

Mark Byers
Mark Byers

Reputation: 839114

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

Upvotes: 5

Related Questions