Home > OS >  Python: checking for duplicates
Python: checking for duplicates

Time:10-14

I'm trying to make a function that rolls dice until all dice rolls are equal, removing the most frequent die from the next roll. What I'm struggling with is finding an easy way to check if the list only contains the same number. I've managed to get as far as getting the same numbers on all dice, but it turns into an infinite loop. Any suggestions as to how I can check if a list is just the same number, so I can use that as a condition to break the loop?

Any help would be most appreciated.

CodePudding user response:

One way to do this is to cast your list to a set().

As sets can only have unique members, the cast will remove any duplicates. So a list of all the same number, when cast to a set will only have one element.

>>> l1 = [1,4,1,1,1]
>>> len(set(l1))
2
>>> l2 = [1,1,1,1,1,1]
>>> len(set(l2))
1

CodePudding user response:

Here's a code for checking if a given list has only one unique value in it.

if len(set(your_list)) == 1:
   break
  • Related