-2

Im currently working on a game which uses lists and gives users choices depending on if there is/isnt duplicates in a list (really basic text based game), however i cant seem to code something that recognises if there is no duplicates without looping through and checking if the count for each number is greater than 1. I really just need something that would check if the list contains no duplicates so that i can then write the rest of the program.

so the psuedocode would look something like this

numbers = [1, 3, 5, 6]

check list for duplicates

if no duplicates:

do x
sam.a
  • 19
  • 1
  • 1
    Possible duplicate of [Check for duplicates in a flat list](https://stackoverflow.com/questions/1541797/check-for-duplicates-in-a-flat-list) – Brad Solomon Sep 08 '17 at 15:08
  • hi @sam-a, please provide an [mcve] – Andy K Sep 08 '17 at 15:08
  • Welcome to Stack Overflow! Please [edit] your question to show [the code you have so far](http://whathaveyoutried.com). You should include at least an outline (but preferably a [mcve]) of the code that you are having problems with, then we can try to help with the specific problem. You should also read [ask]. – Toby Speight Sep 08 '17 at 15:13

2 Answers2

2

Use set function with sorted:

if sorted(set(y)) == sorted(y):
    pass

Set remove duplicates from given list so its easy to check if your list has duplicates. Sorted its optional but if you give user option to input numbers in other order this will be helpful then.

set() sorted()

Simpler solution if you don't need sorted use:

len(y) != len(set(y))

Its faster because u dont need use sort on both lists. Its return True of False.

Check for duplicates in a flat list

Thaian
  • 1,215
  • 2
  • 20
  • 30
0

You can check the length of the set of the list and compare with its regular length:

l = [1, 3, 32, 4]
if len(set(l)) == len(l):
   pass
Ajax1234
  • 69,937
  • 8
  • 61
  • 102