How to check if items are listed only once in python?

I have a list:

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

Please explain to me how to check if an item appears only once in the list?

Please also explain whether all items from 1 to are listed len(a). For example, in the list item 'a', 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!

+5
source share
5 answers
len( set( a ) ) == len( a )

for the first question as well

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

for the second.

+4
source

For your first question, if your elements are hashed, you can create a collection containing the elements and check its length:

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

, , , False ( , True):

def are_all_elements_unique(l):
    seen = set()
    for x in l:
        if x in seen:
            return False
        seen.add(x)
    return True
+5

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

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

will be true only if itemit appears on the list exactly once.

See Pokes answer for second question

+5
source

For the second question you can check

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

I realized that you want something like this:

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

All Articles