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!
len( set( a ) ) == len( a )
for the first question, and
( len( set( a ) ) == len( a ) == max( a ) ) and min( a ) == 1
for the second.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With